swift 具有多个掩码的UIView

jgovgodb  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(197)

我目前有一个带有渐变蒙版的UIView:

let maskLayer = CAGradientLayer()
maskLayer.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
let innerColor = UIColor(white: 1.0, alpha: 1.0).cgColor
let outerColor = UIColor(white: 1.0, alpha: 0.0).cgColor
maskLayer.colors = [outerColor, innerColor, innerColor, outerColor]
maskLayer.locations = [0.0, 0.20, 0.80, 1.00]
maskLayer.startPoint = CGPointMake(0.5, 0);
maskLayer.endPoint = CGPointMake(0.5, 1);
self.myView.layer.mask = maskLayer

这将成功地将渐变蒙版添加到视图的顶部和底部。

提问

有没有一种方法可以让我在视图的中心添加一个额外的圆形遮罩(非渐变)?

zbdgwd5y

zbdgwd5y1#

您可以创建父/容器层,并添加所有遮罩层作为其子层。

let containerMaskLayer = CALayer()

let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(x: 0, y: 0, width: 300, height: 500)
let innerColor = UIColor(white: 1.0, alpha: 1.0).cgColor
let outerColor = UIColor(white: 1.0, alpha: 0.0).cgColor
gradientLayer.colors = [outerColor, innerColor, innerColor, outerColor]
gradientLayer.locations = [0.0, 0.20, 0.80, 1.00]
gradientLayer.startPoint = CGPointMake(0.5, 0);
gradientLayer.endPoint = CGPointMake(0.5, 1);
containerMaskLayer.addSublayer(gradientLayer)

let circleLayer = CAShapeLayer()
let radius: CGFloat = 100.0
circleLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2.0 * radius, height: 2.0 * radius), cornerRadius: radius).cgPath
circleLayer.position = CGPoint(x: 100 - radius, y: 100 - radius)
circleLayer.fillColor = UIColor.white.cgColor
containerMaskLayer.addSublayer(circleLayer)

view.layer.mask = containerMaskLayer

相关问题