Playing with CAGradientLayer — Swift 3.0

Arvin San Miguel
3 min readNov 1, 2016

--

This blog is intended to show basic implementation of CAGradientLayer. 👌

What is CAGradientLayer?

CAGradientLayer is a subclass of the CALayer which is used to draw a color gradient that fills the shape of the layer (within the bounds of any rounded corners). It is one of the easiest layers to play with, since implementing it only takes a couple of lines to add a nice colorful effect in your UI.

Implementing CAGradientLayer

The most basic implementation of the gradient layer only needs two things:

  • Array of colors ( Needs to be in CGColor since CAGradientLayer uses Core Graphics)
  • Size of the Frame of the gradient layer.

But most probably, we wanted to control where our gradient color stops and where to start again.

Here’s a sample code:

You can see in this sample code,

gradient.colors is an array of CGColor objects defining the color of each gradient stop.

gradient.startPoint & gradient.endPoint defines where the gradient starts and ends with respect to the bounds of the layer’s coordinate space. (I always prefer to use CGFloat because it’s easier to estimate the location of the gradient).

Let’s take a look on the differences when playing with the startPoint and endPoint.

at startPoint(0,0) & endPoint(1,0)

at startPoint(0,0) & endPoint(0,1)

at startPoint(0.25,0.25) & endPoint(1,1)

at startPoint(0.75,0.75) & endPoint(0,1)

How about Animation?

Of course! You can animate gradient layers by accessing their properties, In this example, I tried to play with the locations property and used two colors to have this scanner-like effect in my UIView.

And here’s the output:

Hope you can apply it in your awesome apps! 🙌

--

--