ios - 如何使用蒙版裁剪 View ,但使裁剪掉的部分部分不透明而不是隐藏?

标签 ios swift mask alpha

我想裁剪 View 的一部分。我关注了这篇文章:"How to mask one UIView using another UIView" ,这是我当前的代码:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        /// show a green border around the image view's original frame
        let backgroundView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 300))
        backgroundView.layer.borderColor = UIColor.green.cgColor
        backgroundView.layer.borderWidth = 4
        view.addSubview(backgroundView)
        
        let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 200, height: 300))
        imageView.image = UIImage(named: "TestImage")
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        view.addSubview(imageView)
        
        // MARK: - Mask code
        let maskView = UIView(frame: CGRect(x: 80, y: 100, width: 100, height: 100))
        maskView.backgroundColor = .blue /// ensure opaque
        view.addSubview(maskView)
        
        imageView.mask = maskView
        
    }
}

面具工作正常:

<表类=“s-表”> <标题> 不戴口罩 带面具 <正文> Full image with no cropping Only a small square of image visible, the rest is cropped out. A green border indicates the original, uncropped image's frame.

但是,我希望 ImageView 中被裁剪的部分仍然存在,但只是具有较低的 Alpha。它应该是这样的:

Full image with cropping, but the parts that are cropped out are still there. They just have a lower alpha.

我尝试更改 maskView.alpha0.25 ,但这只会使带有 mask 的部分变得不那么不透明。

Cropped image that has 0.25 alpha

如何使裁剪掉的部分仍然存在,但只是更透明一点?

我最好不想创建另一个 View ,因为最终我将在相机预览图层上使用它 - 额外的 View 可能会降低性能。


编辑:matt's answer

我尝试添加一个具有较少 alpha 背景颜色的 subview :

let maskView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 300))
maskView.backgroundColor = UIColor.blue.withAlphaComponent(0.3)

let maskView2 = UIView(frame: CGRect(x: 80, y: 100, width: 100, height: 100))
maskView2.backgroundColor = UIColor.blue.withAlphaComponent(1)
maskView2.alpha = 0

maskView.addSubview(maskView2)

imageView.mask = maskView

但这就是结果:

Entire image has 0.3 alpha

最佳答案

这一切都取决于您为蒙版绘制的颜色的透明度。 (色调——我们通常认为的颜色——是无关紧要的。)遮蔽取决于透明度。 mask 部分透明的区域将使 mask View 部分透明。

因此,将蒙版设置为目标 View 的整个大小,并将整个蒙版设置为部分透明的颜色,除了中心区域为不透明的颜色。

enter image description here

关于ios - 如何使用蒙版裁剪 View ,但使裁剪掉的部分部分不透明而不是隐藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66619237/

相关文章:

ios - 在 Swift iOS 的文本字段中添加分隔符 "-"

ios - 迭代弱引用数组,其中对象符合 Swift 中的协议(protocol)

Pandas 使用掩码对数据帧进行子集化的最佳方法

ios - UITableViewHeaderFooterView 上的约束导致 UIViewAlertForUnsatisfiableConstraints

ios - UIBezierPath 视觉错误?

ios - 如何在 Today 扩展小部件上使用 UIAutomation?

Swift 二维数组可选类型和下标(Beta 3)

ios - MobAD 插页式退出后无法识别触摸 - Swift

javascript - 想要使用 jquery 输入掩码插件验证用户单击 ip 地址字段的按钮

c++ - 多区域 mask OpenCV