前兩天遇到一個問題,需要判定某一點是否落在某一不規則圖形中,翻閱資料之後,發現可以使用貝塞爾曲線完成。
使用貝塞爾曲線,可以繪製各式各樣的不規則曲線和路徑。可以在路徑中添加直線,圓角,圓弧等各式各樣的曲線。
我這裏使用的例子是一個不規則的四邊形。(凹多變形沒有測過)
UIBezierPath *tempPath = [[UIBezierPath alloc] init];
[tempPath moveToPoint:CGPointMake(0, 221)];
[tempPath addLineToPoint:CGPointMake(45, 240)];
[tempPath addLineToPoint:CGPointMake(50, 140)];
[tempPath addLineToPoint:CGPointMake(8, 113)];
[tempPath addLineToPoint:CGPointMake(0, 221)];
[tempPath closePath];
self.path_1 = tempPath;
[tempPath release];
self.path_1 是我定義的一個全局變量,用來存放閉合路徑的。
我使用touchbegin來捕獲落點。
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
if ([self.path_1 containsPoint:point]) {
NSLog(@"####");
}
}
使用UIBezierPath的這個方法- (BOOL)containsPoint:(CGPoint)point;來判定取到的點是否落在我們繪製好的閉合曲線內。
控制檯上輸出####即爲我們成功捕獲到閉合曲線的落點了。