使用渐变填充为CGPath设置动画

时间:2016-08-29 10:39:08

标签: ios swift gradient cabasicanimation cgpath

我可以使用以下代码创建一个带有渐变笔划(清除为红色)的贝塞尔曲线:

let context = UIGraphicsGetCurrentContext()

CGContextBeginTransparencyLayer (context, nil)
let path = createCurvePath()
path.stroke()
CGContextSetBlendMode(context, .SourceIn)

let color1:CGColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0).CGColor
let color2:CGColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1).CGColor

let colors          = [color1, color2]
let colorSpace      = CGColorSpaceCreateDeviceRGB()
let colorLocations :[CGFloat] = [0.0, 0.2]
let gradient        = CGGradientCreateWithColors(colorSpace, colors, colorLocations)
let startPoint      = CGPointMake(20, 20)
let endPoint        = CGPoint(x: rect.size.width, y: rect.size.height)

CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, CGGradientDrawingOptions.DrawsBeforeStartLocation)
CGContextEndTransparencyLayer(context)

我现在想要为绘制的笔画设置动画。 要为笔画设置动画,我添加CAShapeLayer并复制路径。然后我添加一个CABasicAnimation来为被描边的路径设置动画。

self.pathLayer.frame = CGRectMake(0, 0, self.frame.width, self.frame.height)
self.pathLayer.path = path.CGPath

self.pathLayer.strokeColor = UIColor.blueColor().CGColor
self.pathLayer.fillColor = nil
self.pathLayer.lineWidth = 6.0
self.pathLayer.lineJoin = kCALineJoinRound
self.pathLayer.lineCap = kCALineCapRound

self.layer.addSublayer(self.pathLayer)

self.pathAnimation.duration = 1.5
self.pathAnimation.fromValue = NSNumber(float: 0.0)
self.pathAnimation.toValue = NSNumber(float: 1.0)
self.pathAnimation.speed = 1

self.pathLayer.addAnimation(self.pathAnimation, forKey: nil)

如您所见,pathLayer笔触颜色为蓝色。我的问题是如何将渐变应用于路径图层?我尝试使用与非动画线相同的上下文方法,但这对我没有用;我收到了无效的上下文错误。

0 个答案:

没有答案