简体   繁体   English

为CAShapeLayer添加渐变

[英]Add gradient to CAShapeLayer

I got this CAShapeLayer drawing a line in a chart for me: 我得到了这个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
}

Now I'd like to draw this line with a gradient instead of a single color. 现在,我想用渐变色而不是单色来画这条线。 This is what I came up with, but unfortunately it does not draw the line for me. 这就是我想出的,但是不幸的是,这并没有为我划清界限。 Without this added code (lineColors.count == 1) the line is drawn correctly with a single color. 没有此添加的代码(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)
    }
}

Well turns out I was searching more than an hour for this line: 好吧,我在这条线上搜索了一个多小时:

gradientLayer.colors = lineColors

I forgot to map the UIColors objects in this array to CGColorRef objects... This line fixed it for me: 我忘了将此数组中的UIColors对象映射到CGColorRef对象...这一行为我修复了它:

gradientLayer.colors = lineColors.map({$0.cgColor})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM