UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to draw color gradients using CAGradientLayer

Swift version: 5.6

Paul Hudson    @twostraws   

I love CAGradientLayer because it takes just four lines of code to use, and yet looks great because it quickly and accurately draws smooth color gradients use Core Graphics. Here's a basic example:

let layer = CAGradientLayer()
layer.frame = CGRect(x: 64, y: 64, width: 160, height: 160)
layer.colors = [UIColor.red.cgColor, UIColor.black.cgColor]
view.layer.addSublayer(layer)

Note that you need to fill in an array of colors that will be used to draw the gradient. You can provide more than one if you want to, at which point you will also need to fill in the locations array to tell CAGradientLayer where each color starts and stops. Note that you need to specify your colors as CGColor and not UIColor.

If you want to make your gradient work in a different direction, you should set the startPoint and endPoint properties. These are both CGPoints where the X and Y values are between 0 and 1, where 0 is one edge and 1 is the opposite edge. The default start point is X 0.5, Y 0.0 and the default end point is X 0.5, Y 1.0, which means both points are in the center of the layer, but it starts at the top and ends at the bottom.

You might be interested to know that CAGradientLayer happily works with translucent colors, meaning that you can make a gradient that fades out.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 3.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.