Animating a color change in CAGradientLayer.
suggest change// Get the current colors of the gradient.
let oldColors = self.gradientLayer.colors
// Define the new colors for the gradient.
let newColors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
// Set the new colors of the gradient.
self.gradientLayer.colors = newColors
// Initialize new animation for changing the colors of the gradient.
let animation: CABasicAnimation = CABasicAnimation(keyPath: "colors")
// Set current color value.
animation.fromValue = oldColors
// Set new color value.
animation.toValue = newColors
// Set duration of animation.
animation.duration = 0.3
// Set animation to remove once its completed.
animation.isRemovedOnCompletion = true
// Set receiver to remain visible in its final state when the animation is completed.
animation.fillMode = kCAFillModeForwards
// Set linear pacing, which causes an animation to occur evenly over its duration.
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
// Set delegate of animation.
animation.delegate = self
// Add the animation.
self.gradientLayer.addAnimation(animation, forKey: "animateGradientColorChange")
Result :
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents