在UIView顶部添加减法蒙版

时间:2019-03-09 20:08:39

标签: ios cocoa-touch uiview

我想将一个UIView放在另一个UIView上作为减法蒙版。可以这样做吗?

我有一张矩形照片,我想在它上面放一个带有黑色圆角的蒙版。我不想在照片上加上圆角。本质上,遮罩有点像相框,您可以透过它查看。

Photo of a tree with a mask rounding the corners

2 个答案:

答案 0 :(得分: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

希望有帮助!

答案 1 :(得分: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.