4

I am trying to use a UIView as a mask to add in front of another UIView. I need this to create the tutorial of my application. This is the code:

UIView *baseView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
//self.view = baseView;
[self.view addSubview:baseView];
[baseView setBackgroundColor:[UIColor blackColor]];
baseView.userInteractionEnabled = YES;
baseView.alpha = 0.5;

CAShapeLayer *mask = [[CAShapeLayer alloc] init];
mask.frame = baseView.layer.bounds;
CGRect biggerRect = CGRectMake(mask.frame.origin.x, mask.frame.origin.y, mask.frame.size.width, mask.frame.size.height);
CGRect smallerRect = CGRectMake(200.0f, 500.0f, 300.0f, 200.0f);

UIBezierPath *maskPath = [UIBezierPath bezierPath];
[maskPath moveToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMinY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMaxY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(biggerRect), CGRectGetMaxY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(biggerRect), CGRectGetMinY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMinY(biggerRect))];

[maskPath moveToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMinY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMaxY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(smallerRect), CGRectGetMaxY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(smallerRect), CGRectGetMinY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMinY(smallerRect))];

mask.path = maskPath.CGPath;
[mask setFillRule:kCAFillRuleEvenOdd];
mask.fillColor = [[UIColor blackColor] CGColor];
baseView.layer.mask = mask;

In this way I have a black and transparent UIView with a rectangular hole. I would like to make so that if the user touches anywhere else in the UIView apart from the cut part nothing happens. If the user touches anywhere in the cut part, it should be as if the user touched the UIView below it. Is this even possible?

rounak
  • 9,217
  • 3
  • 42
  • 59
Alessandro
  • 4,000
  • 12
  • 63
  • 131
  • See if this similar question and answer help: [Cut transparent hole in UIView][1] [1]: http://stackoverflow.com/questions/9711248/cut-transparent-hole-in-uiview/30994705#30994705 – dichen Jun 23 '15 at 05:56

1 Answers1

1

You may want to override the - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event; method of the view that is acting as your overlay.

From here you can see if the point is within the cut out area, if it is return NO.

You can see this stackoverflow question here that has more info.

The documentation does a reasonable job explaining the relationship between pointInside:withEvent and hitTest:withEvent.

Community
  • 1
  • 1
Bill Wilson
  • 954
  • 6
  • 9