Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a user tapped near a CGPath?

Scenario:

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?

Here's what I had working:

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

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)) { ...

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.

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?

like image 780
Ed Marty Avatar asked Jul 17 '09 14:07

Ed Marty


Video Answer


1 Answers

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) ...
like image 71
rob mayoff Avatar answered Sep 24 '22 22:09

rob mayoff