CAShapeLayer: Hardware-Accelerated Vector Drawing

A CAShapeLayer is a GPU-powered stencil for drawing vector shapes. It renders paths like lines and curves far more efficiently than drawing in `draw(_:)`. Use it for custom UI like progress rings.
WHY IT EXISTS Standard CALayers are rectangular. Drawing custom, non-rectangular shapes by overriding a UIView's draw(_:) method uses the CPU and is inefficient, especially if the shape needs to be redrawn frequently for animations. CAShapeLayer was created to solve this by offloading vector drawing to the GPU.
THE MENTAL MODEL Think of a CAShapeLayer as a specialized hardware tool for vector graphics. You give it a blueprint (a CGPath) and style properties (like fillColor, strokeColor, lineWidth). The GPU then takes over, rasterizing the shape onto the screen incredibly fast. It's offloading the expensive drawing work from the CPU to dedicated graphics hardware.
HOW IT WORKS You create a CAShapeLayer instance and add it to a view's layer hierarchy. You define a shape using a UIBezierPath (or CGPath) and assign it to the layer's path property. The layer then automatically renders this path. Because it's a CALayer subclass, many of its properties like strokeEnd (the percentage of the path that is stroked) are implicitly animatable, meaning Core Animation can interpolate changes on the GPU for you.
WHEN TO USE IT Use CAShapeLayer for any custom shape that isn't a simple rectangle. This includes circular avatars with borders, pie charts, loading spinners, custom button shapes, and drawing lines or graphs. It's especially powerful when these shapes need to animate, as property changes can be hardware-accelerated.
WHEN NOT TO USE IT For simple rectangular views with a background color and corner radius, a standard CALayer with its cornerRadius property is sufficient and simpler. For complex bitmap images or textures, CALayer's contents property is the right tool. CAShapeLayer is specifically for vector paths, not raster images.
ONE CANONICAL EXAMPLE Creating a circular progress bar. You define a circular UIBezierPath. You create two CAShapeLayers: one for the background track and one for the progress itself. Both share the same circular path. The progress layer's strokeEnd property is then animated from 0.0 to 1.0 to show progress, which Core Animation handles smoothly on the GPU without forcing any CPU-based redraws.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.