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 on top of it. But unsure how to get a black CALayer with a .3 alpha.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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];
回答2:
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)
回答3:
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
回答4:
Did you think about adding a UIView
with black backgroundColor and 0.3 alpha as a subview to the image view?
回答5:
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];