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
Did you think about adding a UIView
with black backgroundColor and 0.3 alpha as a subview to the image view?
This is similar to MDT's answer except using CALayer properties:
UIView *blackOverlay = [[UIView alloc] initWithFrame: imageView.frame];
blackOverlay.layer.backgroundColor = [[UIColor blackColor] CGColor];
blackOverlay.layer.opacity = 0.3f;
[self.view addSubview: blackOverlay];
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 <QuartzCore/QuartzCore.h>
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
Swift 5 Version:
func addOverlay(on view: UIView) {
let overlay: UIView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
overlay.backgroundColor = UIColor.gray
view.addSubview(overlay)
}
Something like this?
UIView *overlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0, myImageView.frame.size.width, myImageView.frame.size.height / 2)];
[overlay setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
[myImageView addSubview:overlay];
Thanks to Mick MacCallum
Swift 3 Version
let overlay: UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell.imageView.frame.size.width, height: cell.imageView.frame.size.height))
overlay.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.1)
cell.imageView.addSubview(overlay)
I have used for Swift 2.2
let overlay: UIView = UIView(frame: CGRectMake(0, 0, cell.imageView.frame.size.width, cell.imageView.frame.size.height))
overlay.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.1)
cell.imageView.addSubview(overlay)