How do I mask the UIView to highlight the selection?

The problem I am facing is simple (and less abstract than the question itself). I am looking for a solution to make an area of ​​an image (selection) stand out while the rest of the image is faded or grayed out. You can compare the effect to the interface you see in Photoshop, for example, when you crop an image. The image will be grayed out and the area to be cropped will be transparent.

My initial idea was to use cloaking for this (hence the question), but I'm not sure if this is a viable approach and, if so, how to proceed.


source to share

1 answer

Not sure if this is the best way, but it should work.

First, you take a screenshot of the view.

UIGraphicsBeginImageContextWithOptions(captureView.bounds.size, view.opaque, 0.0);
[captureView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();


This snippet is "stolen" and slightly modified from here: Poor quality viewing context on iPad

Then you can create a matte scale image at the same size as the original (screenshot).

Follow the clear and simple instructions on How to mask an image .

Then you create UIImageView

, set the masked image as an image and add it on top of your original view. You can also set backgroundColor

this UIImageView

to your liking.


An easier way would probably be to use view.layer.mask

which is "an additional layer whose alpha channel is used as a mask to choose between the layer's background and the result of compositing the layer's content with its filtered background." (from CALayer class link)

Some literature:

UIView class reference

CALayer class reference

And a simple example of how one can make a mask (possibly hidden) of another UIView:

UIView masking



All Articles