Skip to content

CAGradientLayer ​

CAGradientLayer represents a gradient layer: it draws a color gradient within its own rectangle. The gradient can run along a straight line, outward from a center, or around a center in a full turn.

It's a layer. Like other sublayers, you set its frame yourself and add it under some view's layer. Give it at least two colors, or nothing is visible.

CAGradientLayer doesn't fire events. Its properties are only changed by the app's code, so there are no change notifications.

Inheritance: EventTarget → NSObject → CALayer → CAGradientLayer

For how to make a gradient background and change its direction, see the guide Drawing rounded corners, shadows, gradients, and shapes with layers.

Constructor ​

CAGradientLayer()

Creates a gradient layer. Its size is 0 × 0 pt and it has no colors.

Instance properties ​

Also inherits properties from CALayer; commonly used ones are frame and cornerRadius.

PropertyDescription
colorsThe colors the gradient passes through in order
locationsThe position of each color
startPointThe start point
endPointThe end point
typeThe shape of the gradient

Instance methods ​

CAGradientLayer has no methods of its own. Also inherits methods from CALayer.

Unit coordinates ​

startPoint and endPoint use unit coordinates: (0, 0) is the layer's top-left corner and (1, 1) is the bottom-right corner, regardless of the layer's actual size. The default runs from (0.5, 0) to (0.5, 1), that is, top to bottom.

What the two points mean for each type:

typeEffectstartPointendPoint
'axial'Colors change along a straight lineStart of the lineEnd of the line
'radial'Colors change outward from the center of a circleCenter of the circleDetermines the circle's size
'conic'Colors change in a full turn around the centerCenterDetermines the starting angle

How 'radial' and 'conic' look when drawn is not verified in the simulator.

Examples ​

Gradient from top left to bottom right ​

js
const card = new UIView();
card.frame = new CGRect(20, 100, 300, 160);

const gradient = new CAGradientLayer();
gradient.colors = ['#5856D6', '#FF2D55'];
gradient.startPoint = new CGPoint(0, 0);
gradient.endPoint = new CGPoint(1, 1);
gradient.frame = card.bounds;
card.layer.addSublayer(gradient);

Effect: the card's background shades from purple at the top-left corner to pink at the bottom-right corner.

Corresponding iOS API ​

ObjCJS
[CAGradientLayer layer]new CAGradientLayer()
gradient.colors = @[(id)a.CGColor, (id)b.CGColor]gradient.colors = ['#000', '#fff']
gradient.locations = @[@0, @0.3, @1]gradient.locations = [0, 0.3, 1]
gradient.type = kCAGradientLayerRadialgradient.type = 'radial'

See also ​