在UIImageView上加上0.3不透明的黑色覆盖

我有一个UIImageView,我想在它上面添加一个黑色的覆盖。 这样做的最好方法是什么,而不必重写drawRect? 我正在考虑在其上添加一个CALayer。 但不确定如何获得一个.3阿尔法的黑色CALayer。

像这样的东西?

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]; 

感谢Mick MacCallum

Swift 3版本

 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) 

我用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) 

MDT答案是正确的。 这只是在UIView旁边使用CAGradientLayer另一种方法。 我认为这将使你想要更多的graphics选项。

首先你应该添加

 #import <QuartzCore/QuartzCore.h> 

到您的ViewController.m和任何你想添加这个覆盖到你的UIImage使用的地方:

 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]; 

我希望这会帮助你做到这一点

你有没有想过添加一个带有backgroundColor和0.3 alpha的UIView作为图像视图的子视图?

除了使用CALayer属性之外,这与MDT的答案类似:

 UIView *blackOverlay = [[UIView alloc] initWithFrame: imageView.frame]; blackOverlay.layer.backgroundColor = [[UIColor blackColor] CGColor]; blackOverlay.layer.opacity = 0.3f; [self.view addSubview: blackOverlay];