为啥我无法使用 CAGradientLayer 的掩码
Posted
技术标签:
【中文标题】为啥我无法使用 CAGradientLayer 的掩码【英文标题】:Why i fail to use mask of CAGradientLayer为什么我无法使用 CAGradientLayer 的掩码 【发布时间】:2017-06-21 15:20:25 【问题描述】:我想画一个这样的按钮
所以我使用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)
时,我得到了这样的结果:
谁能告诉我为什么?
【问题讨论】:
【参考方案1】:你设置的是fillColor
而不是strokeColor
,改变这一行
maskLayer.fillColor = UIColor.white.cgColor
有了这个
maskLayer.fillColor = UIColor.clear.cgColor
maskLayer.strokeColor = UIColor.white.cgColor
【讨论】:
天哪,我误解了面具的概念!以上是关于为啥我无法使用 CAGradientLayer 的掩码的主要内容,如果未能解决你的问题,请参考以下文章
为啥我的 CAGradientLayer 为所有更改设置动画?
为啥在模态视图控制器被解除后 CAGradientLayer 从视图中删除