我正在尝试使用 Apples 方法来检测一个点是否在 UIBezierPath 上。然而,它返回一个“无效的上下文”。
正如您从 NSlog 中看到的,我正在传递一个 UIBezierPath 和 A 点来检查。就我而言,是一个接触点。
我不明白为什么。有人可以向我解释或指出正确的方向吗?
NSLOG -----
Path <UIBezierPath: 0x7f57110>
Contains point Path <UIBezierPath: 0x7f57110>
Touch point 425.000000 139.000000
<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextAddPath: invalid context 0x0
<Error>: CGContextPathContainsPoint: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0
NO
直接来自 Apples Documentation 关于如何确定路径中的点
- (BOOL)containsPoint:(CGPoint)point onPath:(UIBezierPath *)path inFillArea:(BOOL)inFill {
NSLog(@"contains point Path %@", path);
NSLog(@"Touch point %f %f", point.x, point.y );
CGContextRef context = UIGraphicsGetCurrentContext();
CGPathRef cgPath = path.CGPath;
BOOL isHit = NO;
// Determine the drawing mode to use. Default to detecting hits on the stroked portion of the path.
CGPathDrawingMode mode = kCGPathStroke;
if (inFill) { // Look for hits in the fill area of the path instead.
if (path.usesEvenOddFillRule)
mode = kCGPathEOFill;
else
mode = kCGPathFill;
}
// Save the graphics state so that the path can be removed later.
CGContextSaveGState(context);
CGContextAddPath(context, cgPath);
// Do the hit detection.
isHit = CGContextPathContainsPoint(context, point, mode);
CGContextRestoreGState(context);
return isHit;
}
这是我的 touchesBegan 方法。我在 NSMutableArray 中有我的路径。我解析数组以检查我所有的路径,看看是否有任何被触及。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint curPoint = [[touches anyObject] locationInView:self];
for (int i = 0; i < [pathInfo count]; i++){
NSArray *row = [[NSArray alloc] initWithArray:[pathInfo objectAtIndex:i]];
UIBezierPath *path = [row objectAtIndex:0];
NSLog(@"Path %@", path);
if ([self containsPoint:curPoint onPath:path inFillArea:NO]){
NSLog(@"YES");
} else {
NSLog(@"NO");
}
}
}