jam*_*mes 7 iphone cocoa-touch objective-c
可能重复:
如何检查用户是否在CGPath附近轻敲?
我正在从这里关注Apple的指南
尝试仅在我的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;
}
Run Code Online (Sandbox Code Playgroud)
当我打电话给我时,我得到:
错误: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];
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试调用touchesMoved中的containsPoint函数,如下所示:
if (![self containsPoint:c onPath:[self createPath] inFillArea:NO]) return;
Run Code Online (Sandbox Code Playgroud)
当您当前未绘图时(如在touchesMoved方法中),没有当前上下文,因此UIGraphicsGetCurrentContext()将返回 NULL。
由于您对上下文所做的只是使用其当前路径,因此您也可以使用CGPathContainsPoint而不是CGContextPathContainsPoint.
| 归档时间: |
|
| 查看次数: |
4716 次 |
| 最近记录: |