gpt4 book ai didi

ios - 向 CAShapeLayer 添加渐变

转载 作者:行者123 更新时间:2023-11-30 12:08:36 24 4
gpt4 key购买 nike

我用这个 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/

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