gpt4 book ai didi

swift - 为什么我无法使用 CAGradientLayer 的蒙版

转载 作者:行者123 更新时间:2023-11-30 12:22:06 25 4
gpt4 key购买 nike

我想画一个像这样的按钮enter image description here

所以我使用 CAGradientLayerCAShapeLayerUIBezierPath 。代码如下:

    let gradientLayer: CAGradientLayer = CAGradientLayer.init()
gradientLayer.startPoint = CGPoint.init(x: 0, y: 0.7)
gradientLayer.endPoint = CGPoint.init(x: 1, y: 0.1)
gradientLayer.locations = [NSNumber.init(value: 0.25), NSNumber.init(value: 0.5), NSNumber.init(value: 0.75), NSNumber.init(value: 1)]
gradientLayer.colors = [UIColor.blue.cgColor, UIColor.green.cgColor, UIColor.yellow.cgColor, UIColor.orange.cgColor]
gradientLayer.frame = CGRect.init(origin: self.bounds.origin, size: self.frame.size)
gradientLayer.borderColor = UIColor.clear.cgColor
gradientLayer.borderWidth = 1

//make mask layer
let hGap: CGFloat = 1
let vGap: CGFloat = 1
let maskLayer: CAShapeLayer = CAShapeLayer.init()
let maskPath: UIBezierPath = UIBezierPath.init()
let viewWidth = self.frame.size.width - hGap * 2
let viewHeight = self.frame.size.height - vGap * 2
maskPath.move(to: CGPoint.init(x: viewHeight / 2, y: 0))
maskPath.addLine(to: CGPoint.init(x: viewWidth - viewHeight / 2, y: 0))
maskPath.addArc(withCenter: CGPoint.init(x: viewWidth - viewHeight / 2, y: viewHeight / 2), radius: viewHeight / 2, startAngle: (CGFloat(1.5) * CGFloat.pi), endAngle: CGFloat.pi / 2, clockwise: true)
maskPath.addLine(to: CGPoint.init(x: viewHeight / 2, y: viewHeight))
maskPath.addArc(withCenter: CGPoint.init(x: viewHeight / 2, y: viewHeight / 2), radius: viewHeight / 2, startAngle: CGFloat.pi / 2, endAngle: CGFloat(1.5) * CGFloat.pi, clockwise: true)
maskPath.close()
maskLayer.path = maskPath.cgPath
maskLayer.borderColor = UIColor.clear.cgColor
maskLayer.fillColor = UIColor.white.cgColor
maskLayer.frame = CGRect.init(x: vGap, y: hGap, width: viewWidth, height: viewHeight)
//maskLayer.frame = CGRect.init(x: 0, y: 0, width: viewWidth, height: viewHeight)

//TODO: Why mask not work
//gradientLayer.mask = maskLayer


self.layer.cornerRadius = Constant.kViewSize.height / 2
self.layer.masksToBounds = true
self.layer.borderColor = UIColor.clear.cgColor
self.layer.addSublayer(gradientLayer)
self.layer.addSublayer(maskLayer)//i use sublayer instead


self.addSubview(self.titleLabel)
self.titleLabel.snp.makeConstraints { maker in
maker.center.equalTo(self.snp.center)
}

当我使用gradientLayer.mask = maskLayer而不是self.layer.addSublayer(maskLayer)时,我得到了这样的结果:

enter image description here

谁能告诉我为什么?

最佳答案

您正在设置 fillColor 而不是 strokeColor,请更改此行

maskLayer.fillColor = UIColor.white.cgColor

有了这个

maskLayer.fillColor = UIColor.clear.cgColor
maskLayer.linesColor = UIColor.white.cgColor

关于swift - 为什么我无法使用 CAGradientLayer 的蒙版,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44680169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com