【问题标题】:Add semi-transparent mask to CALayer?向CALayer添加半透明蒙版?
【发布时间】:2013-03-26 00:41:03
【问题描述】:

我正在尝试使 UIImageView 的周围区域变暗,并保留一部分(我用我的蒙版定义)。

现在我正在定义我的蒙版并设置我的 imageView.layer.mask,但是它并没有使图像的其余部分变暗,而是将其完全移除。

我想要的效果类型示例:

我得到的示例:

参考文档提到遮罩使用它的图层 alpha,所以我尝试操纵遮罩的不透明度。但是,这似乎只会影响我想留下的部分的不透明度,而图像的其余部分仍然被完全剪切掉。

谁能指出我做错了什么?谢谢。

这是我的代码:

CAShapeLayer *mask = [CAShapeLayer layer];
GMutablePathRef path = CGPathCreateMutable();

CGPathMoveToPoint(path, nil, 1052, 448);
CGPathAddLineToPoint(path, nil, 2, 484);
CGPathAddLineToPoint(path, nil, 54, 1263);
CGPathAddLineToPoint(path, nil, 56, 1305);
CGPathAddLineToPoint(path, nil, 380, 1304);
CGPathAddLineToPoint(path, nil, 1050, 1311);
CGPathCloseSubpath(path);
mask.path = path;
CGPathRelease(path);

//mask.opacity = 0.5; //doesn't affect the surrounding portion, only the cut out area.
self.imageView.layer.mask = mask;

【问题讨论】:

  • 另一种选择:使用带有遮罩的深色(但不是完全不透明)叠加层来隐藏箭头周围的部分。

标签: ios objective-c calayer mask cashapelayer


【解决方案1】:

如果其他人有同样的问题:如果目标是使图层变暗,则蒙版不合适。但是如果你需要让图片的一部分透明或者半透明,那绝对是个不错的选择。

例如,此代码可以存在于 NSView 子类中:

    let imageLayer = CALayer()
    let maskLayer = CAShapeLayer()

    let ovalPath = NSBezierPath(ovalIn: bounds)
    maskLayer.path = ovalPath
    maskLayer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
    maskLayer.frame = bounds
    maskLayer.backgroundColor = NSColor.black.withAlphaComponent(0.2).cgColor

    imageLayer.contents = NSImage(named: "sampleImage")
    imageLayer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
    imageLayer.frame = bounds


    imageLayer.mask = maskLayer

这为imageLayer 中的椭圆形“洞”提供了 0.2 的不透明度。

【讨论】:

    【解决方案2】:

    你做错的是首先使用图层蒙版。您正在尝试使图像的某个区域变暗或变暗。这根本不是图层蒙版的作用!基本上,图层蒙版会穿透现有图层,导致其背后显示出来。这正是你发现的:

    它正在完全删除它

    是的,因为这就是图层蒙版的作用!如果你不想这样,你为什么要使用图层蒙版?

    您想要的只是将第二个图像视图(或只是一个子图层)放在第一个图像视图上。它包含您绘制的图像。它是透明的,除非它具有半透明的深色填充。这将使背后的东西变暗。您使用剪切路径来定义没有得到深色填充的区域。

    或者,通过使用合成或可能使用 CIFilter 在图像视图上绘制来更改图像视图中的图像。

    【讨论】:

      猜你喜欢
      • 2013-12-05
      • 2014-03-27
      • 2016-09-20
      • 1970-01-01
      • 2011-12-17
      • 2014-06-23
      • 1970-01-01
      • 2018-11-26
      • 2023-04-03
      相关资源
      最近更新 更多