0

I am using a mask to remove unwanted parts of an image. This all works correctly using the code below.

I then attach a tap gesture event to the image. However, I want the tap event gesture to be applied the result of the masked image rather than the full size of the UIimage frame. Any suggestions on how to do this?

CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:self.graphicMask] CGImage];
mask.frame = CGRectMake(0, 0, 1024, 768);

[self.customerImage  setImage:[UIImage imageNamed:self.graphicOff]];
[[self.customerImage  layer] setMask:mask];
self.customerImage.layer.masksToBounds = YES;

//add event listener
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(customerSelected)];
[self.customerImage addGestureRecognizer:tap];

Update - My solution

In the end I decided not to use a mask and instead check the pixel colour of the touched point (as suggested by the correct answer). I used code from another question https://stackoverflow.com/a/3763313/196361.

I added a method to the view controller that is called whenever the view is touched.

- (void)touchesBegan:(NSSet*)touches
{
//check the colour of a touched point on the customer image
CGPoint p = [(UITouch*)[touches anyObject] locationInView:self.customerImage];

UIImage *cusUIImg = self.customerImage.image;

unsigned char pixel[1] = {0};
CGContextRef context = CGBitmapContextCreate(pixel,1, 1, 8, 1, NULL, kCGImageAlphaOnly);
UIGraphicsPushContext(context);
[cusUIImg drawAtPoint:CGPointMake(-p.x, -p.y)];
UIGraphicsPopContext();
CGContextRelease(context);
CGFloat alpha = pixel[0]/255.0;


//trigger click event for this customer if not already selected
if(alpha == 1.000000)
    [self customerSelected];
}
Community
  • 1
  • 1
Max
  • 1,175
  • 3
  • 12
  • 22

1 Answers1

2

If your mask is fairly rectangular then the easiest way would be to add transparent UIView on top with frame matching the masked region. Then you would add UITapGestureRecognizer directly to the invisible view.

EDIT

If you want your taps to be accepted based on the mask exactly then you can read the pixel color of mask in the tap location and check against your threshold.

Bartosz Ciechanowski
  • 10,293
  • 5
  • 45
  • 60
  • Unfortunately my masks are not that retangular. Is there a way to get the frame of the masked region? – Max Nov 01 '12 at 16:00