前两天遇到一个问题,需要判定某一点是否落在某一不规则图形中,翻阅资料之后,发现可以使用贝塞尔曲线完成。
使用贝塞尔曲线,可以绘制各式各样的不规则曲线和路径。可以在路径中添加直线,圆角,圆弧等各式各样的曲线。
我这里使用的例子是一个不规则的四边形。(凹多变形没有测过)
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;来判定取到的点是否落在我们绘制好的闭合曲线内。
控制台上输出####即为我们成功捕获到闭合曲线的落点了。