Swift version: 5.6
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
If you want to make your gradient work in a different direction, you should set the
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.
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 3.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.