【发布时间】:2012-06-28 09:07:23
【问题描述】:
我有一个 UIImageView,我想在它上面添加一个黑色叠加层。无需覆盖drawRect的最佳方法是什么?我正在考虑在它上面添加一个 CALayer。但不确定如何获得具有 0.3 alpha 的黑色 CALayer。
【问题讨论】:
标签: iphone objective-c ios ipad calayer
我有一个 UIImageView,我想在它上面添加一个黑色叠加层。无需覆盖drawRect的最佳方法是什么?我正在考虑在它上面添加一个 CALayer。但不确定如何获得具有 0.3 alpha 的黑色 CALayer。
【问题讨论】:
标签: iphone objective-c ios ipad calayer
您是否考虑过在图像视图中添加一个带有黑色背景颜色和 0.3 alpha 的 UIView 作为子视图?
【讨论】:
这样的?
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];
【讨论】:
colorWithPatternImage: 预期功能的公然滥用......而且......这样做也将丧失使用图像视图的能力内置在内容模式中,例如方面填充/适合等。
colorWithPatternImage: 作为解决方案。我通常会创建一个包含两个子视图的UIView:一个UIImageView 和一个具有叠加层的UIView。我认为 Apple 不允许在 IB 中创建子视图这一事实足以暗示我们不应该引导人们走这条路。
这类似于 MDT 的答案,除了使用 CALayer 属性:
UIView *blackOverlay = [[UIView alloc] initWithFrame: imageView.frame];
blackOverlay.layer.backgroundColor = [[UIColor blackColor] CGColor];
blackOverlay.layer.opacity = 0.3f;
[self.view addSubview: blackOverlay];
【讨论】:
MDT 的答案是正确的。这只是在 UIView 旁边使用 CAGradientLayer 的另一种方式。我认为它会通过更多图形选项实现您想要的。
首先你应该添加
#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];
希望对你有所帮助
【讨论】:
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)
【讨论】:
Swift 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)
}
【讨论】: