

The code above shows how the gradient is added to a view. It is also actually rather simple but the documentation is somewhat terse, so this tutorial is here to explain it in more depth.Ī CAGradientLayer, at its simplest, defines a gradient between two points, each having a different colour. It’s fast and efficient because, in common with the Core Graphics frameworks in general, it’s built on top of OpenGL. The BasicsĬAGradientLayer is part of the iOS/macOS Core Animation framework. Whether your app needs static gradients for custom UI components or animated gradients for snazzy controls, you should certainly consider using CAGradientLayer before anything more complex. If you need to use OpenGL then you probably know already! When to Use CAGradientLayerĬAGradientLayer is the sweet spot between ease-of-use and functionality. It definitely only makes sense if you’re already using OpenGL, for instance in a game. The third, using OpenGL directly, is easily the most complex.

The second, using Core Graphics, is more complex than CAGradientLayer since you need to manipulate the graphics context during the rendering phase of a view, but it can be useful if your gradient needs to be highly dynamic, or if your application is already doing Core Graphics rendering. In modern iOS programming, we generally avoid images wherever possible. Also the gradient colours are fixed and cannot be animated at all. This is easy but inflexible: you must ensure you have the correct image resolutions for each screen size you need to support. The first and most basic is to simply use an image from a design package such as Photoshop. Each has its pros and cons, which we’ll briefly discuss.

There are three other ways of creating gradients you should be aware of before diving in.
How to make a background picture with swift how to#
This tutorial will teach you how to create iOS gradients in Swift using CAGradientLayer.
