UIBezierPath: Drawing Custom Shapes in Code

UIBezierPath is a digital pen for drawing custom shapes. You define a path with lines and curves, then fill or stroke it. It's essential for custom charts, icons, or non-rectangular views.
WHY IT EXISTS Standard UI components like labels and buttons are fundamentally rectangles. To create any shape that isn't a simple box—like a star, a wavy line, or a custom icon—apps need a way to describe a custom boundary. UIBezierPath provides this low-level, programmatic drawing capability.
THE MENTAL MODEL Imagine you have a pen and a piece of graph paper (your UIView). UIBezierPath is the set of instructions you give the pen. "Lift the pen and move to coordinate (10, 20)." This is moveTo(). "Now, draw a straight line to (50, 50)." This is addLine(to:). Finally, you command the system to either trace the lines with ink (stroke) or color in the resulting shape (fill).
HOW IT WORKS You create a UIBezierPath object. You can start with a predefined shape (like a rectangle or oval) or build a custom one from scratch. To build a custom path, you first call moveTo(point:) to set the starting position. Then, you append segments like lines (addLine(to:)), arcs (addArc(withCenter:...)), or curves (addCurve(to:...)). Once the path is defined, you render it inside a view's draw(_:) method by setting properties on the current graphics context (like color and line width) and then calling the path's stroke() or fill() methods.
WHEN TO USE IT Use it for creating custom UI controls (e.g., a star-shaped rating button), drawing data visualizations (line graphs, pie charts), creating masks to clip other views into non-rectangular shapes, or adding simple decorative elements like borders with specific rounded corners.
WHEN NOT TO USE IT For performance-intensive graphics like games, use a dedicated framework like SpriteKit or Metal. For simple rectangular layouts, standard UIViews with background colors and the cornerRadius property are far more efficient. UIBezierPath is for vector drawing, not for displaying raster images like JPEGs or PNGs (use UIImage for that).
ONE CANONICAL EXAMPLE To draw a simple triangle, you subclass UIView, override its draw(_:) method, and add this code: let path = UIBezierPath(); path.move(to: CGPoint(x: 50, y: 10)); path.addLine(to: CGPoint(x: 90, y: 90)); path.addLine(to: CGPoint(x: 10, y: 90)); path.close(); UIColor.blue.setFill(); path.fill(); This creates a path, connects three points, closes the shape, and fills it with blue.
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.