20

我有一个 UIImageView,我想在它上面添加一个黑色叠加层。无需覆盖drawRect的最佳方法是什么?我正在考虑在它上面添加一个 CALayer。但不确定如何获得具有 0.3 alpha 的黑色 CALayer。

4

6 回答 6

53

像这样的东西?

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];
于 2012-06-27T00:21:58.497 回答
17

感谢米克·麦卡勒姆

斯威夫特 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)
于 2016-05-10T10:45:02.803 回答
8

MDT 的答案是正确的。这只是使用CAGradientLayer旁边的另一种方式UIView。我认为它会通过更多的图形选项来满足您的需求。

首先你应该添加

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

我希望这会帮助你做到

于 2012-06-27T06:16:49.073 回答
5

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

UIView *blackOverlay = [[UIView alloc] initWithFrame: imageView.frame];
blackOverlay.layer.backgroundColor = [[UIColor blackColor] CGColor];
blackOverlay.layer.opacity = 0.3f;
[self.view addSubview: blackOverlay];
于 2012-06-27T01:02:08.643 回答
4

你有没有想过UIView在图像视图中添加一个带有黑色背景颜色和 0.3 alpha 的子视图?

于 2012-06-27T00:08:36.707 回答
2

斯威夫特 5版本:

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)
}
于 2020-10-30T08:03:48.103 回答