Scenario:
I have a set of CGPath
s. 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
?
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) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With