掩盖UIImageview的触摸区域

时间:2012-11-01 13:01:34

标签: objective-c

我正在使用遮罩去除图像中不需要的部分。这一切都可以正常使用下面的代码。

然后我将轻击手势事件附加到图像上。但是,我希望将tap事件手势应用于蒙版图像的结果,而不是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];
}

1 个答案:

答案 0 :(得分:2)

如果你的面具是相当矩形的,那么最简单的方法是在顶部添加透明的UIView,并将框架与遮罩区域相匹配。然后,您可以将UITapGestureRecognizer直接添加到不可见的视图中。

修改

如果您希望根据蒙版完全接受您的点击,那么您可以在点击位置读取蒙版的像素颜色并检查您的阈值。