我得到了这个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)
}
}
最佳答案
好吧,事实证明我正在为这个行搜索一个多小时:
gradientLayer.colors = lineColors
我忘了将此数组中的UIColors对象映射到CGColorRef对象...
这行为我修复了它:
gradientLayer.colors = lineColors.map({$0.cgColor})
关于ios - 为CAShapeLayer添加渐变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46365733/