Detect touches only on non-transparent pixels of UIImageView, efficiently

前端 未结 3 683
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 00:34

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

Consider an image like the one below, displayed with UI

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 00:53

    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;
    }
    

    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.

    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.

提交回复
热议问题