In this blog post we will look at how to use the CAGradientLayer API and create some cool animated gradient effects like the ones seen in
apps like instagram.
The CAGradientLayer is a CALayer that allows us to draw gradients. It can accept any number of colors as input and blend those colors
together to render a continuous gradient of colors.
The code above creates a diagonal gradient between two colors. The direction of the gradient can be controlled by the adjusting the
start and end points of the gradient.
Since all CALayer proporties are animatable we can create a CABasicAnimation on the colors property of the CAGradientLayer to show a smooth
transition from one gradient to another.
The code above changes the animates the gradient over a duration of 5 seconds.
We can expand on this approach and create a continuous looping animation where one gradient seamlessly blends into another over time. To implment
a continuous gradient we must extend our view controller to conform to the CAAnimationDelegate protocol. An example of such an implementation
is shown here.
In the code above we start off by creating 3 different gradients. We the append them in an array called gradientSet, out animation will loop through the array and blend one gradient into another. We keep a simple index currentGradient to keep track of which gradient is to be displayed and change the toValue of our gradientAnimation to that particular gradient. Since we’re going to be rerendering our gradientlayer we set the drawAsynchronously flag to true.
CAGradientLayer is a powerful API and can be used in conjuntion with other CALayer APIs provided by iOS to create some really cool effects in a very simple