有效地检测仅触摸UIImageView的非透明像素

有效地检测仅触摸UIImageView的非透明像素

本文介绍了有效地检测仅触摸UIImageView的非透明像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何有效地检测 UIImageView 的非透明像素上的触摸?

How would you detect touches only on non-transparent pixels of a UIImageView, efficiently?

考虑一个图像如下所示,用 UIImageView 显示。目标是仅在触摸发生在图像的非透明(在这种情况下为黑色)区域时,手势识别器才会响应。

Consider an image like the one below, displayed with UIImageView. The goal is be to make the gesture recognisers respond only when the touch happens in the non-transparent (black in this case) area of the image.


  • 覆盖或,虽然这种方法可能非常低效,因为在触摸事件期间会多次调用这些方法。

  • 检查是否单个像素是透明的可能会产生意外的结果,因为手指大于一个像素。检查命中点周围的像素圆形区域,或尝试找到朝向边缘的透明路径可能会更好。

  • Override hitTest:withEvent: or pointInside:withEvent:, although this approach might be terribly inefficient as these methods get called many times during a touch event.
  • Checking if a single pixel is transparent might create unexpected results, as fingers are bigger than one pixel. Checking a circular area of pixels around the hit point, or trying to find a transparent path towards an edge might work better.

  • 它会是很好地区分图像的外部和内部透明像素。在示例中,零点内的透明像素也应视为有效。

  • 如果图像有变换会发生什么?

  • 图像是否可以处理硬件加速?

推荐答案

这是我的快速实现:(基于)

Here's my quick implementation: (based on 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;
}

这假设图像与<$ c位于同一坐标空间$ C>点。如果继续缩放,您可能必须在检查像素数据之前转换

This assumes that the image is in the same coordinate space as the point. If scaling goes on, you may have to convert the point before checking the pixel data.

看起来很漂亮快点给我。我估计约。此方法调用0.1-0.4 ms。它没有内部空间,可能不是最佳的。

Appears to work pretty quickly to me. I was measuring approx. 0.1-0.4 ms for this method call. It doesn't do the interior space, and is probably not optimal.

这篇关于有效地检测仅触摸UIImageView的非透明像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:14