可能的重复:
如何检查用户是否在 CGPath 附近点击? https://stackoverflow.com/questions/1143704/how-can-i-check-if-a-user-tapped-near-a-cgpath
我从这里遵循苹果的指南
http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html
尝试仅检测 UIBezierPath 的描边部分上的触摸事件。如果我使用 UIBezierPath 方法 containsPoint,它工作正常,但它会检测 UIBezierPath 的笔划和填充部分上的触摸事件,并且我希望它仅发生在笔划部分上。
按照 Apple 的指南(在链接的清单 3-6 中),我创建了这个函数:
- (BOOL)containsPoint:(CGPoint)point onPath:(UIBezierPath*)path inFillArea:(BOOL)inFill
{
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;
}
当我调用它时,我得到:
错误:CGContextSaveGState:无效上下文 0x0
错误:CGContextAddPath:无效上下文 0x0
错误:CGContextPathContainsPoint:无效上下文 0x0
错误:CGContextRestoreGState:无效上下文 0x0
这是我的视图的 drawRect 函数,以及创建路径的代码:
- (UIBezierPath *) createPath {
static UIBezierPath *path = nil;
if(!path) {
path = [[UIBezierPath bezierPathWithOvalInRect:CGRectMake(35, 45, 250, 250)] retain];
path.lineWidth = 50.0;
[path closePath];
}
return path;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
*/
- (void)drawRect:(CGRect)rect
{
// Drawing code
//draw a circle
UIBezierPath *aPath = [self createPath];
//set stroke width
aPath.lineWidth = 50.0;
//set stroke color
[[UIColor blueColor] setStroke];
//stroke path
[aPath stroke];
//close path
[aPath closePath];
//add a label at the "top"
UILabel *topLabel;
topLabel = [[UILabel alloc]initWithFrame:CGRectMake(120, -5, 80, 25)];
topLabel.text = @"The Top";
[self addSubview:topLabel];
}
然后我尝试调用 TouchMoved 内部的 containsPoint 函数,如下所示:
if (![self containsPoint:c onPath:[self createPath] inFillArea:NO]) return;