如何检查用户是否在CGPath附近轻敲?

Ed *_*rty 10 iphone quartz-graphics

场景:

我有一套CGPaths.它们大多只是线条(即不是封闭的形状).它们以绘图方式绘制在屏幕上UIView.

如何检查用户是否在其中一条路径附近轻敲?

这就是我的工作:

UIGraphincsBeginImageContext(CGPathGetBoundingBox(path));
CGContextRef g = UIGraphicsGetCurrentContext();
CGContextAddPath(g,path);
CGContextSetLineWidth(g,15);
CGContextReplacePathWithStrokedPath(g);
CGPath clickArea = CGContextCopyPath(g);  //Not documented
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

所以我正在做的是创建一个图像上下文,因为它具有我需要的功能.然后我将路径添加到上下文中,并将行宽设置为15.此时描绘路径将创建我可以在其中检查以查找点击的点击区域.所以我通过告诉上下文将路径转换为描边路径,然后将该路径复制回另一个CGPath来获得该描述路径.之后,我可以查看:

if (CGPathContainsPoint(clickArea,NULL,point,NO)) { ...
Run Code Online (Sandbox Code Playgroud)

这一切都运作得很好,但是CGContextCopyPath,由于显而易见的原因,使用无证,似乎是一个坏主意.关于CGContext为此目的而做一个公正,也有一定的愚蠢.

那么,有没有人有任何想法?如何检查用户是否在任何区域附近(在这种情况下,在15个像素内)轻敲CGPath

rob*_*off 22

在iOS 5.0及更高版本中,可以使用CGPathCreateCopyByStrokingPath以下命令更简单地完成此操作:

CGPathRef strokedPath = CGPathCreateCopyByStrokingPath(path, NULL, 15,
    kCGLineCapRound, kCGLineJoinRound, 1);
BOOL pointIsNearPath = CGPathContainsPoint(strokedPath, NULL, point, NO);
CGPathRelease(strokedPath);

if (pointIsNearPath) ...
Run Code Online (Sandbox Code Playgroud)

  • 在Swift 3.0中:`path.copy(strokingWithWidth:CGFloat ...)` (4认同)