NullHypothesis NullHypothesis - 1 year ago 133
iOS Question

Adding a layer of color over a UIImage

I was hoping to make my UIImage "highlight" briefly upon being tapped. Not sure of the color yet, but let's say blue for arguments sake. So you tap the image, it briefly looks blue and then it navigates you to a details page to edit something on another screen.

From some initial reading it seems the right course of action is to use the Quartz framework and do this:

imageView.layer.backgroundColor = UIColor.blueColor()
imageView.layer.opacity = 0.7

I guess the idea would be you change the background of the layer behind the image, and then by setting the opacity of the image, the blue "bleeds through" a little bit, giving you a slightly blue image?

When I try the above, however, a blue border goes around the image itself, and based upon the opacity, the blue is either dark or light. The actual image does not become any more blue, but it does react to the opacity (meaning if I set it to something like .1, the image is very faded and barely visible). Why does the image react correctly, but not show blue?

Thanks so much!

Answer Source

As far as I know changing the opacity will change the opacity for the WHOLE view, meaning not just the UIImage that the UIImageView holds. So instead of fading to reveal the UIImageView's background color, instead the opacity of the whole view is just decreased as you're seeing.

Another way you could do it though would be to add an initially transparent UIView on top of your UIImageView and change its opacity instead:

UIView *blueCover = [[UIView alloc] initWithFrame: myImageView.frame];
blueCover.backgroundColor = [UIColor blueColor];
blueCover.layer.opacity = 0.0f;
[self.view addSubview: blueCover];

[UIView animateWithDuration:0.2f animations^{
  blueCover.layer.opacity = 0.5f
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download