将渐变添加到 CAShapeLayer
Posted
技术标签:
【中文标题】将渐变添加到 CAShapeLayer【英文标题】:Add gradient to CAShapeLayer 【发布时间】:2017-09-22 13:15:45 【问题描述】:我让这个 CAShapeLayer 在图表中为我画了一条线:
open func generateLayer(path: UIBezierPath) -> CAShapeLayer
let lineLayer = CAShapeLayer()
lineLayer.lineJoin = lineJoin.CALayerString
lineLayer.lineCap = lineCap.CALayerString
lineLayer.fillColor = UIColor.clear.cgColor
lineLayer.lineWidth = lineWidth
lineLayer.strokeColor = lineColors.first?.cgColor ?? UIColor.white.cgColor
lineLayer.path = path.cgPath
if dashPattern != nil
lineLayer.lineDashPattern = dashPattern as [NSNumber]?
if animDuration > 0
lineLayer.strokeEnd = 0.0
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = CFTimeInterval(animDuration)
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pathAnimation.fromValue = NSNumber(value: 0 as Float)
pathAnimation.toValue = NSNumber(value: 1 as Float)
pathAnimation.autoreverses = false
pathAnimation.isRemovedOnCompletion = false
pathAnimation.fillMode = kCAFillModeForwards
pathAnimation.beginTime = CACurrentMediaTime() + CFTimeInterval(animDelay)
lineLayer.add(pathAnimation, forKey: "strokeEndAnimation")
else
lineLayer.strokeEnd = 1
return lineLayer
现在我想用渐变而不是单一颜色来绘制这条线。这是我想出的,但不幸的是它并没有为我划清界限。如果没有这个添加的代码 (lineColors.count == 1),线条就可以正确地用单一颜色绘制。
fileprivate func show(path: UIBezierPath)
let lineLayer = generateLayer(path: path)
layer.addSublayer(lineLayer)
if lineColors.count > 1
let gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
gradientLayer.frame = self.bounds
gradientLayer.colors = lineColors
gradientLayer.mask = lineLayer
layer.addSublayer(gradientLayer)
【问题讨论】:
【参考方案1】:原来我为这条线搜索了一个多小时:
gradientLayer.colors = lineColors
我忘记将此数组中的 UIColors 对象映射到 CGColorRef 对象... 这条线为我修好了:
gradientLayer.colors = lineColors.map($0.cgColor)
【讨论】:
以上是关于将渐变添加到 CAShapeLayer的主要内容,如果未能解决你的问题,请参考以下文章