如何高效地检测 UIImageView
的非透明像素上的触摸?
考虑如下图,使用 UIImageView
显示。目标是让手势识别器仅在触摸发生在图像的非透明(本例中为黑色)区域时做出响应。
想法
- 覆盖
hitTest:withEvent:
或pointInside:withEvent:
,尽管这种方法可能非常低效,因为这些方法在触摸事件期间会被多次调用。 - 检查单个像素是否透明可能会产生意想不到的结果,因为手指比一个像素大。检查命中点周围的圆形像素区域,或尝试找到通向边缘的透明路径可能会更好。
奖金
- 最好能区分图像的外部和内部透明像素。在示例中,零内的透明像素也应被视为有效。
- 如果图像有变换会怎样?
- 图像处理可以硬件加速吗?
最佳答案
这是我的快速实现:(基于 Retrieving a pixel alpha value for a UIImage )
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
//Using code from https://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage
unsigned char pixel[1] = {0};
CGContextRef context = CGBitmapContextCreate(pixel,
1, 1, 8, 1, NULL,
kCGImageAlphaOnly);
UIGraphicsPushContext(context);
[image drawAtPoint:CGPointMake(-point.x, -point.y)];
UIGraphicsPopContext();
CGContextRelease(context);
CGFloat alpha = pixel[0]/255.0f;
BOOL transparent = alpha < 0.01f;
return !transparent;
}
这假定图像与点
在同一坐标空间中。如果继续缩放,您可能必须在检查像素数据之前转换点
。
对我来说似乎工作得很快。我正在测量大约。此方法调用需要 0.1-0.4 毫秒。它不处理内部空间,可能不是最佳选择。
关于iphone - 仅在 UIImageView 的非透明像素上有效地检测触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13291919/