2017-09-22 154 views
0

我得到這個CAShapeLayer繪製圖表中的線對我來說:添加漸變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) 
    } 
} 

回答

0

那麼原來我此行尋找了一個多小時:

gradientLayer.colors = lineColors 

我忘記了UIColors對象數組來CGColorRef對象在地圖... 這條線固定它me:

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