Search code examples
iosios6calayer

CALayer containsPoint with mask not working


I have a UIView that have a CALayer mask:

// Getting the right mask image
UIImage *myimage = [UIImage imageNamed:[NSString stringWithFormat:@"img%d", imageIndex]];

// Scaling image to fit UIView
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
[myimage drawInRect:self.bounds];
myimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[self.layer setMasksToBounds:YES];

// Setting mask
UIImage *_maskingImage = myimage;
CALayer *_maskingLayer = [CALayer layer];
_maskingLayer.frame = self.bounds;
[_maskingLayer setContents:(id)[_maskingImage CGImage]];
[self.layer setMask:_maskingLayer];

When the user later short press (UILongPressGestureRecognizer *) the UIView I just want a action to happend if the user taps in the UIView layer mask (for now containsPoint always returns YES):

// Object is a UIView
CALayer *layer = [Object.layer mask];

// Sender is a UILongPressGestureRecognizer
location2 = [sender locationInView:Object];

// The position is correct
NSLog(@"%@", NSStringFromCGPoint(location2));

if ([layer containsPoint:location2]){
     NSLog(@"HELLO WORLD!");
     return;
}

Help, please?


Solution

  • My book gives two suggestions. If you know the bounding path of the mask drawing, you can use CGPathContainsPoint. Or, if the layer in question is transparent on the outside and opaque on the inside, you can examine the pixel at the tapped location to see if it is transparent or not.

    http://www.apeth.com/iOSBook/ch18.html#_hit_testing

    Scroll down to the section "Hit-testing for drawings".