tezvyn:

Canvas in SwiftUI

AI-drafted, machine-checkedSource: developer.apple.comintermediate
Canvas in SwiftUI

Canvas is SwiftUI's view for fast, immediate mode drawing. Instead of composing many shape views, you draw paths, text, and images directly into a GraphicsContext, which is far cheaper for complex or animated graphics.

WHY IT EXISTS SwiftUI's normal model represents every visual element as a view in a tree that gets diffed and laid out on every update. That works well for buttons and text but breaks down for a chart with two thousand data points or a waveform redrawing sixty times a second: creating that many view structs every frame is wasteful. Canvas exists to let developers draw directly, bypassing the view tree entirely for performance sensitive graphics.

THE MENTAL MODEL Think of the rest of SwiftUI as arranging furniture, describing what should exist and letting the system figure out placement. Canvas hands you a paintbrush and a blank wall instead. You are told the size of the wall, and inside the closure you issue direct drawing commands, paths, fills, strokes, text, with no intermediate view objects created at all.

HOW IT WORKS Canvas takes a closure with a GraphicsContext and a CGSize. The context exposes imperative drawing methods, fill, stroke, draw for text and images, drawLayer for grouped effects, all backed by Core Graphics under the hood. You build Path values describing geometry, then call context methods to render them, applying transforms, blend modes, or opacity as needed. Canvas also accepts a list of resolved symbols, SwiftUI views pre rendered into images you can place at arbitrary points, which is how you mix ordinary SwiftUI content into imperative drawing.

WHEN IT MATTERS It matters whenever a view redraws often or contains many primitives: audio waveforms, live charts, custom gauges, particle systems, or heatmaps. Using ordinary views for these produces visible frame drops and heavy memory churn from constant view diffing. The footgun is reaching for Canvas by default: it loses SwiftUI's accessibility tree, hit testing, and animation interpolation, so simple static graphics are usually still better as plain Shape or Image views.

ONE CONCRETE EXAMPLE A fitness app renders a heart rate graph updating every second with a rolling window of three hundred points. Built with three hundred individual Path shapes, scrolling stutters. Rebuilt with a single Canvas that loops over the data array and strokes one continuous Path inside the GraphicsContext, the same graph renders smoothly because SwiftUI never creates per point view objects.

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.