3

Is there a way to know if a 'tap' is inside or outside the masked area of a UIView? I'm using CoreGraphics to mask the UIView.

Tap Location Diagram

So far my code goes something like this..

- (void)viewDidLoad {

    UIGestureRecogniser *r = [[UIGestureRecogniser alloc] initWithTarget:self action:@selector(gestCall:)];
    [self addGestureRecogniser:r];

}

- (void)gestCall:(UIGestureRecogniser *)gestRec {
     if ("somthing") {
        // outside of mask
     } else {
        // inside of mask
     }
}

Thank you.

Benjamin
  • 663
  • 8
  • 23

2 Answers2

5

I've finally found the solution I was looking for. So for the benefit of any one trying to find is a CGPoint is inside any CGPath.

It's simple.

UIBezierPath *p = [UIBezierPath bezierPathWithCGPath:anyCGPath];

BOOL isInPath = [p containsPoint:anyCGPoint];
Benjamin
  • 663
  • 8
  • 23
2

Basically you need to check the touch coordinate and decide whether is falls into the mask area or not. Override the hitTest:withEvent: and account for the image mask. You can use [[[self layer] presentationLayer] hitTest:aPoint] or [[[self layer] mask] hitTest:aPoint] in your overridden `-[UIView hitTest:withEvent:].

[EDIT]

Check if a user tapped near a CGPath might help to find answer to your question.

[EDIT]

Do following in your Gesture Handler to figure out to process tap or not.

  1. Specify the center of the circle (This would be UIView.Center as CGPoint)
  2. Specify the radius of pie chart
  3. When user tap on the view, get the location as point - CGPoint and calculate point.x*point.x+point.y*point.y (Circle formulae) and this value must be less than or equal to the square of the radius i.e radius*radius. If this condition satisfied then your tap point is inside the circle otherwise outside.

Hope that makes clear.

Community
  • 1
  • 1
Paresh Masani
  • 7,474
  • 12
  • 73
  • 139
  • To clarify I want to know whether a CGPoint is inside a CGPath. I thought that might be a simple method. I'm not that experienced with Core Graphics. – Benjamin Oct 19 '12 at 16:40
  • Okay. What are you trying to achieve exactly? Which gestures you want? Is it only single tap? Is your mask always in circle shape? – Paresh Masani Oct 19 '12 at 17:05
  • Check the SO link I posted. You might need workout little bit there. – Paresh Masani Oct 19 '12 at 17:18
  • I'm trying use a UIPanGestureRecogniser to display a label on top of a pie chart. However I want to make the hit area only within the chart not the bounds of the UIView. – Benjamin Oct 22 '12 at 08:06
  • Edited the ans. It's simple math. Hope you will get it working. – Paresh Masani Oct 22 '12 at 08:17