以下是我在项目中使用的代码,用于在UIView中创建一个圆形和一个矩形遮罩,您可以将UIBezierPath
行替换为相同的弧形代码:
func createCircleMask(view: UIView, x: CGFloat, y: CGFloat, radius: CGFloat, downloadRect: CGRect){
self.layer.sublayers?.forEach { ($0 as? CAShapeLayer)?.removeFromSuperlayer() }
let mutablePath = CGMutablePath()
mutablePath.addArc(center: CGPoint(x: x, y: y + radius), radius: radius, startAngle: 0.0, endAngle: 2 * 3.14, clockwise: false)
mutablePath.addRect(view.bounds)
let path = UIBezierPath(roundedRect: downloadRect, byRoundingCorners: [.topLeft, .bottomRight], cornerRadii: CGSize(width: 5, height: 5))
mutablePath.addPath(path.cgPath)
let mask = CAShapeLayer()
mask.path = mutablePath
mask.fillRule = kCAFillRuleEvenOdd
mask.backgroundColor = UIColor.clear.cgColor
view.layer.mask = mask
}
传递同一个UIView,它会删除之前的图层并在同一个UIView上应用新的遮罩。
这里mask.fillRule = kCAFillRuleEvenOdd
很重要。如果你注意到有3个mutablePath.addPath()
函数,那么kCAFillRuleEvenOdd
做的是,它首先使用弧形创建一个孔,然后添加该视图边界的矩形,再添加另一个遮罩以创建第二个孔。