I have a UIImageView and I wanted to add a black overlay on top of it. What is the best way of doing this without having to override drawRect? I was thinking of adding a CALayer
The MDT answer is correct. This is just another way to use a CAGradientLayer
beside of UIView
. I think it will make what you want with more graphical options.
first you should add
#import
to your ViewController.m
and any place that you want to add this overlay to your UIImage
use:
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = myImageView.layer.bounds;
gradientLayer.colors = [NSArray arrayWithObjects:
(id)[UIColor colorWithWhite:0.9f alpha:0.7f].CGColor,
(id)[UIColor colorWithWhite:0.0f alpha:0.3f].CGColor,
nil];
gradientLayer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:0.5f],
nil];
//If you want to have a border for this layer also
gradientLayer.borderColor = [UIColor colorWithWhite:1.0f alpha:1.0f].CGColor;
gradientLayer.borderWidth = 1;
[myImageView.layer addSublayer:gradientLayer];
I hope this will help you make it