Appcoda

A Beginner’s Guide to Bezier Paths and Shape Layers

The process of developing apps includes amongst other things the creation of the user interface (UI) and all those simple or complicated views that appear on screen. There are different ways and different approaches to draw a simple “screen” of an app: To use already made graphics by designers, implement the UI in code, use Interface Builder, use a combination of them, and so on. However, there are always times that you need to create custom shaped views programmatically, and if you don’t know how, then problems start to arise.

These problems can be avoided however, by using the UIBezierPath class, which according to the documentation, is what you need to create vector-based paths. In simple words, with this class you can define custom paths that describe any shape, and use those paths to achieve any custom result you want. With it, it’s possible to create from simple shapes like rectangles, squares, ovals and circles to highly complex shapes by adding lines to a path, both straight and curved, between sets of points.

A bezier path that is created by the above class cannot stand on its own. It needs a Core Graphics context where it can be rendered to. There are three ways to get a context like that:

  1. To use a CGContext context.
  2. To subclass the UIView class which you want to draw the custom shape to, and use its draw(_:) method provided by default. The context needed is provided automatically then.
  3. To create special layers called CAShapeLayer objects.

From all three options, we’ll meet the last two in this tutorial, so we don’t miss our scope with the Core Graphics programming details.

→ Keep Reading on Appcoda