如何检查用户是否在CGPath附近窃听? [英] How can I check if a user tapped near a CGPath?

查看:71
本文介绍了如何检查用户是否在CGPath附近窃听?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:

我有一组 CGPath s。它们大多只是线条(即非闭合形状)。它们是使用 UIView 的draw方法绘制在屏幕上的。

I have a set of CGPaths. They are mostly just lines (i.e. not closed shapes). They are drawn on the screen in a UIView's draw method.

如何检查用户是否点击了

How can I check if the user tapped near one of the paths?

这是我工作的地方:

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

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

So what I'm doing is creating an image context, because it has the functions I need. I then add the path to the context, and set the line width to 15. Stroking the path at this point would create the click area I can check inside of to find clicks. So I get that stroked path by telling the context to turn the path into a stroked path, then copying that path back out into another CGPath. Later, I can check:

if (CGPathContainsPoint(clickArea,NULL,point,NO)) { ...

一切正常,但是 CGContextCopyPath ,没有证件,出于显而易见的原因,似乎是个坏主意。为此目的制作 CGContext 也存在一定的困惑。

It all worked well and good, but the CGContextCopyPath, being undocumented, seemed like a bad idea to use for obvious reasons. There's also a certain kludginess about making a CGContext just for this purpose.

那么,有人有什么想法吗?如何检查用户是否在 CGPath 的任何区域附近(在这种情况下,在15像素之内)点击?

So, does anybody have any ideas? How do I check if a user tapped near (in this case, within 15 pixels) of any area on a CGPath?

推荐答案

在iOS 5.0及更高版本中,可以使用 CGPathCreateCopyByStrokingPath

In iOS 5.0 and later, this can be done more simply using CGPathCreateCopyByStrokingPath:

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

if (pointIsNearPath) ...

这篇关于如何检查用户是否在CGPath附近窃听?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆