So I Wanted To Draw A Gradient

Gretchen, Stop Trying To Make Gradients Happen

Introduction

NOTE: Updated for iOS 12 and Swift 4.2

If there’s one API that irritated me in the beginning of my career as an iOS developer, it was CAGradientLayer. As powerful as it is, it’s also very verbose and that can be really confronting for a newbie.

Nevertheless, the time came where I had to draw a gradient in an app. No images. I turned to CAGradientLayer because I already understood it, however it confused my team, who were less familiar with it.

For example, a gradient will be drawn between 0 and 1, on both the X (horizontal) and Y (vertical) axes. This is hard to explain, so let’s look at the image below.

The Plane

A CALayer gradient uses these points. I sometimes see people printing this, and drawing on it to assist with planning.

The Code

Hopefully this helps. It’s a wrapper around using CAGradientLayer which gives CAGradientLayer a simpler interface. Just initialise with what you want, set the frame, and add the sublayer!

Usage

In an ordinary UIViewController, or on a UIView or a UIView-inheriting object, use the following code:

let gradient = CAGradientLayer(start: .center, end: .bottomRight, colors: [UIColor.black.cgColor, UIColor.white.cgColor], type: .radial)
gradient.frame = view.bounds
view.layer.addSublayer(gradient)

Easy, no?


If you liked this post, please consider clapping for it. I notice each one and appreciate them quite a lot. Thank-you!