Take the 2-minute tour ×

There are three layers added to UIView. One layer draws a rectangle. One draws a circle. One draws a polygon. The layer's opacity is no. When I touched the polygon, I want to get the correct layer which draws the polygon. And the three layers are full filled to the view. I have implemented this. But I don't know if we have better solution to solve it .My way is like this: 1.Drawing the content using -drawLayer:inContext. store the CGPath that you used. 2.In the UIView's -touchedEnded:withEvent method. using CGPathContainsPoint() to detect if the touch point is contained by the CGPath.

Maybe this is the stupid way to solve this. Anyone who can tell me how to solve it better?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

If you need an accurate hit test for path's I'm afraid you have to check/iterate the layer hierarchy yourself if the point is inside your path using CGPathContainsPoint as you suggested.

While iterating you could optimize it by skipping layers where the point is outside their frame.

For less fine grained control you can get the touched layer by using CALayers

- (CALayer *)hitTest:(CGPoint)thePoint


If you have a layer hierarchy with a nesting level < 1000 (which is almost always true) I would not worry too much.

share|improve this answer
Another question is about the CGPath,When I used CGPathContainsPoint() to detect the point. I need to cache the CGPath. So I didn't release it immediately .if I use CGPathRelease() in the -drawLayer:inContext:,I can't get the CGPath in the -touchédEnded:withEvent:. I don't know where should I release the CGPath in the layer. –  pyanfield Feb 8 '12 at 13:57
You don't need to cache the path, use CAShapeLayer for drawing shapes. It has a path property you can always access. –  Erik Aigner Feb 8 '12 at 14:12
yes, you are right. thanks. –  pyanfield Feb 9 '12 at 9:32
add comment

Your Answer


