When using transparent PNG images in iOS development sometimes it’s useful to limit touches to where the image is not transparent.
UIButton, there’s the most excellent OBShapedButton by Ole Begemann. At Robot Media we also needed this for UIImageView. After asking about this problem on StackOverflow and studying
OBShapedButton, I decided to create RMShapedImageView and open-source it on GitHub.
RMShapedImageView is a
UIImage subclass that overrides
pointInside:withEvent:. This method is called to determine if a touch is inside the view. In our case, we only want to return
YES if the corresponding pixels are not transparent (
alpha > 0).
RMShapedImageView.mto your project.
- Replace your
RMShapedImageVieweither in code or Interface Builder (by setting the Class of your
RMShapedImageView works with retina and non-retina images, as well as transformed views. It’s particularly useful is you’re using gesture recognisers. Currently supports only two content modes:
UIViewContentModeTopLeft. More will be added in time.
Touches are inexact things and querying the alpha value of a single pixel might be too strict, even more so if the image is scaled down. Furthermore, if the image has shadows you might also want to ignore touches on them.
RMShapedImageView has two configuration options to work around these problems:
shapedTransparentMaxAlpha: maximum alpha value that will be considered transparent. 0 by default.
shapedPixelTolerance: number of pixels around the point that will be examined. If at least one of them has alpha bigger than
YES. 0 by default.
The project also includes a demo and bare-bones unit tests and is distributed under the Apache License 2.0. You’re more than welcome to fork it and improve.