在UIImageView上添加0.3不透明度的黑色叠加层

时间:2012-06-27 00:06:41

标签: iphone objective-c ios ipad calayer

我有一个UIImageView,我想在它上面添加一个黑色覆盖。在不必覆盖drawRect的情况下,这样做的最佳方法是什么?我想在它上面添加一个CALayer。但不确定如何获得带有.3 alpha的黑色CALayer。

6 个答案:

答案 0 :(得分:47)

这样的东西?

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

答案 1 :(得分:16)

感谢Mick MacCallum

Swift 3 版本

    static String ImgNameMole = "(project location)/WpfApplication3/Images/Green-icon.png";

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Image Mole = new Image();
        Mole.Width = 15;
        Mole.Height = 15;
        Mole.Margin = new Thickness(0, 0, 0, 0);
        ImageSource MoleImage = new BitmapImage(new Uri(ImgNameMole));
        Mole.Source = MoleImage;

        Grid.Children.Add(Mole);
    }

我用于 Swift 2.2

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)

答案 2 :(得分: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];

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

答案 3 :(得分:4)

您是否考虑过将带有黑色backgroundColor和0.3 alpha的UIView作为子视图添加到图像视图中?

答案 4 :(得分:4)

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

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

答案 5 :(得分:2)

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)
}