我想画一个像这样的按钮
所以我使用CAGradientLayer
,CAShapeLayer
和UIBezierPath
。像这样的代码:
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)
时,得到的结果如下:有人可以告诉我为什么吗?
最佳答案
您正在设置fillColor
而不是strokeColor
,请更改此行maskLayer.fillColor = UIColor.white.cgColor
有了这个maskLayer.fillColor = UIColor.clear.cgColor maskLayer.strokeColor = UIColor.white.cgColor
关于swift - 为什么我无法使用CAGradientLayer的蒙版,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44680169/