在UIView上添加减法蒙版

问题描述 投票:0回答:2

我想把UIView放在另一个UIView的顶部作为减法掩码。有可能吗?

我有一张长方形的照片,我想在它上面放一个黑色圆角的面具。我不想把圆角放在照片本身上。基本上,面具有点像你可以看透的相框。

Photo of a tree with a mask rounding the corners

ios cocoa-touch uiview
2个回答
0
投票

我曾用this作为参考。它基本上是在CAShapeLayer顶部的UIView上建立一个UIImageView。这就是你需要的:

// Add image view to the root view
let image = UIImage(named: "SomeImage.jpg")
let imageView = UIImageView(frame: view.bounds)
imageView.image = image
view.addSubview(imageView)

// Add mask view on the of image view
let maskView = UIView(frame: view.bounds)
maskView.backgroundColor = .black
view.addSubview(maskView)

// The layer that defines your maskView's behavior
let maskLayer = CAShapeLayer()
maskLayer.frame = maskView.bounds

// Create the frame for the circle.
let radius: CGFloat = 100.0
let roundedRectPath = UIBezierPath(roundedRect: maskView.frame, cornerRadius: radius)

let path = UIBezierPath(rect: maskView.bounds)

// Append the rounded rect to the external path
path.append(roundedRectPath)

maskLayer.fillRule = .evenOdd
maskLayer.path = path.cgPath
maskView.layer.mask = maskLayer

这是结果:

enter image description here

希望有所帮助!


0
投票

我有与其他面具类似的想法,但只需使用UIView掩码。

             let maskView = UIView.init()
            maskView.frame = view.bounds


            let shape = CAShapeLayer.init()
            shape.path =  UIBezierPath.init(ovalIn: maskView.bounds).cgPath
            shape.fillColor = UIColor.white.cgColor


            maskView.layer.addSublayer(shape)
            maskView.backgroundColor = UIColor.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.0)
            view.mask = maskView // view is the imageView.
© www.soinside.com 2019 - 2024. All rights reserved.