我正在使用蒙版来删除图像中不需要的部分。使用下面的代码,这一切都可以正常工作。
然后我将点击手势事件附加到图像。但是,我希望将点击事件手势应用于蒙版图像的结果,而不是 UIimage 框架的完整大小。关于如何做到这一点的任何建议?
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];
更新 - 我的解决方案
最后我决定不使用蒙版,而是检查触摸点的像素颜色(如正确答案所示)。我使用了另一个问题的代码https://stackoverflow.com/a/3763313/196361。
我向视图控制器添加了一个方法,每当触摸视图时都会调用该方法。
- (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];
}