我曾用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
这是结果:
希望有所帮助!
我有与其他面具类似的想法,但只需使用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.