如何到达CGPath进行命中测试?

Pat*_*pel 3 core-graphics objective-c cgpath

我有一个开放的CGPath/UIBezierPath,如果用户触摸它,我想检测它,即一个点是否在距路径一定距离内.路径是开放的(即线/曲线,而不是形状).它可以包含直线和弯曲元素.如何到达测试路径的距离?

Pat*_*pel 7

似乎CGPath/UIBezierPath都没有这样做的功能.编辑:根据@ nielsbot的建议,您可以使用编写自定义实现CGPathApply(…).计算到弯曲部分的距离并非如此微不足道.

然而,我找到了一种实现我最初目标的巧妙方法,即测试路径:CGPathCreateCopyByStrokingPath(…).

- (BOOL)isPoint:(CGPoint)p withinDistance:(CGFloat)distance ofPath:(CGPathRef)path
{
    CGPathRef hitPath = CGPathCreateCopyByStrokingPath(path, NULL, distance*2, kCGLineCapRound, kCGLineJoinRound, 0);
    BOOL isWithinDistance = CGPathContainsPoint(hitPath, NULL, p, false);
    CGPathRelease(hitPath);
    return isWithinDistance;
}
Run Code Online (Sandbox Code Playgroud)

为了获得更好的性能,您可以缓存hitPath.也可以通过将原始路径添加到hitPath使用来用于封闭路径CGPathAddPath(…)