Bart Jacobs
Bart Jacobs

Reputation: 9082

How to mask a UIView to highlight a selection?

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

My initial idea was to use masking for this (hence the question), but I am not sure if this is a viable approach and, if it is, how to proceed.

Upvotes: 3

Views: 2262

Answers (1)

Rok Jarc
Rok Jarc

Reputation: 18865

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

First, you create a screenshot of the view.

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

This snippet is 'stolen' and slightly modified from here: Low quality of capture view context on iPad

Then you could create a grayscale mask image of same dimensions as the original (screenshot).

Follow the clear & simple instructions on How to Mask an Image.

Then you create UIImageView, set the masked image as it's image and add it on top of your original view. You also might want to set the backgroundColor of this UIImageView to your liking.

EDIT:

A simpler way would probably be using view.layer.mask, which is "an optional layer whose alpha channel is used as a mask to select between the layer's background and the result of compositing the layer's contents with its filtered background." (from CALayer class reference)

Some literature:

UIView Class Reference

CALayer Class Reference

And a simple example how mask can be made with (possibly hidden) another UIView:

Masking a UIView

Upvotes: 3

Related Questions