A SwiftUI workout screen draws a 5,000-sample heart-rate trace as separate Shape views and stutters; when do you switch to Canvas or drawingGroup?
answer
- one view instead of thousands
- immediate mode, GraphicsContext
- offscreen image of a subtree
- what each gives up
basics
~20 sThousands of Shape views are thousands of views to manage. Canvas draws everything inside one view through a GraphicsContext but loses per-element accessibility and interaction; drawingGroup keeps the views and flattens them into one offscreen image.
solid answer
~40 s5,000 `Shape` views give SwiftUI 5,000 views to identify, lay out and draw, and that count is what I remove. `Canvas { context, size in … }` (iOS 15) is one view: its renderer receives a `GraphicsContext`, so I build one `Path` for the trace and call `context.stroke(_:with:lineWidth:)` once. Apple's documentation says a canvas offers no interactivity or accessibility for individual elements, so I give it a single accessibility label and hit-test with my own maths. `drawingGroup()` is different: the views stay, but the subtree is composited into an offscreen image before display, which helps with many layered shapes, shadows or blends. It only captures content SwiftUI rasterizes itself, so UIKit-backed views show a placeholder. I measure in Instruments before and after either change.
code
swift · 25 linesimport SwiftUI
struct HeartRateTrace: View {
let samples: [Double] // one reading per second of a long workout
var body: some View {
Canvas { context, size in
guard samples.count > 1,
let low = samples.min(), let high = samples.max(), high > low
else { return }
let step = size.width / CGFloat(samples.count - 1)
var line = Path()
for (index, bpm) in samples.enumerated() {
let point = CGPoint(
x: CGFloat(index) * step,
y: size.height * (1 - (bpm - low) / (high - low))
)
if index == 0 { line.move(to: point) } else { line.addLine(to: point) }
}
context.stroke(line, with: .color(.red), lineWidth: 1.5)
}
.frame(height: 180)
.accessibilityLabel("Heart rate during the workout")
}
}go deeper
Recall that Canvas draws with a GraphicsContext inside one view and that drawingGroup flattens a group of views into an image.
Explain what a GraphicsContext can do, why the order of its state changes matters, and how symbols let a canvas stamp SwiftUI views.
Diagnose the cost as view count or compositing, pick Canvas or drawingGroup accordingly, measure the result, and handle the accessibility and interaction you give up.
Set the team rule for custom drawing: when a screen may leave the view hierarchy for Canvas, and how accessibility parity is reviewed when it does.
## Why many Shape views get expensive A SwiftUI view is a cheap struct, but each view in the hierarchy is still something SwiftUI has to **identify, lay out and render**. A heart-rate trace built as a `ForEach` over 5,000 samples, each a small `Circle` or a `Path` segment wrapped in its own view, asks SwiftUI to manage 5,000 views every time the data changes. On a long workout that becomes visible as dropped frames while scrolling or updating. The fix is to reduce the number of things SwiftUI manages, not to make each one cheaper. SwiftUI offers two different tools for that. ## Canvas: immediate-mode drawing `Canvas` (iOS 15) is **one view** whose content you draw yourself. Its renderer closure receives an `inout GraphicsContext` and the canvas size: - build one `Path` for the whole trace and call `context.stroke(_:with:lineWidth:)` once, or loop and call `context.fill(_:with:)` per point; - draw an `Image` or a `Text` with `context.draw(_:at:)` or `context.draw(_:in:)`, resolving it once with `context.resolve(_:)` when you draw it repeatedly; - clip with `clip(to:)`, add filters with `addFilter(_:)`, set `opacity` and `blendMode`, translate and scale the coordinate system. The initializer also takes three options: - `opaque:` declares that the canvas covers its whole area; - `colorMode:` picks the working colour space, `.nonLinear` by default; - `rendersAsynchronously:`, `false` by default, lets the canvas present its contents asynchronously. Apple's `GraphicsContext` documentation stresses that **order matters**: state changes such as a clip or filter apply only to later drawing. A copy of the context (`var masked = context`) carries its own state while drawing into the same layer. To stamp a SwiftUI view many times, pass it in the `symbols:` builder of `Canvas(opaque:colorMode:rendersAsynchronously:renderer:symbols:)`, tag it, and draw the result of `context.resolveSymbol(id:)`: ```swift import SwiftUI struct BadgeWall: View { let badges: [String] var body: some View { Canvas { context, size in guard let medal = context.resolveSymbol(id: "medal") else { return } for index in badges.indices { let point = CGPoint(x: CGFloat(index % 20) * 18 + 9, y: CGFloat(index / 20) * 18 + 9) context.draw(medal, at: point) } } symbols: { Image(systemName: "medal.fill") .foregroundStyle(.yellow) .tag("medal") } } } ``` The price is spelled out in Apple's documentation: a canvas **does not offer interactivity or accessibility for individual elements**, including views passed as symbols. You give the canvas one accessibility label or summary, and you hit-test taps with your own maths. Nor does SwiftUI interpolate what the renderer draws; motion means redrawing, typically driven by a timeline, which belongs with animation. For a real data chart with axes and selection, Swift Charts is the dedicated framework. ## drawingGroup: flattening a subtree `drawingGroup(opaque:colorMode:)` keeps your views but **composites the subtree into an offscreen image before display**. It suits many overlapping shapes with shadows, blurs or blend modes, where compositing layer after layer is the cost. The views remain views: they keep their layout and their own modifiers. Apple's documentation adds a hard limit: the image only includes content SwiftUI **rasterizes itself** — text, images, shapes and composites of them. Views composited by Core Animation, such as complex controls, web views, media players and most UIKit-backed views, appear as a placeholder instead. An offscreen pass is not free, so applying it to a light view can cost more than it saves. `compositingGroup()` sounds similar but is a different tool: Apple documents it as making ancestor effects such as opacity and blend mode take effect on the group before the subtree is rendered, not as flattening the subtree into an image. ## Choosing | | Many Shape views | `Canvas` | `drawingGroup()` | |---|---|---|---| | Views SwiftUI manages | one per element | one | one per element | | Per-element gestures and accessibility | yes | no | the views keep their modifiers | | UIKit-backed content | yes | no | placeholder | | Best for | dozens of interactive elements | thousands of plain marks, particles | layered effects on SwiftUI-drawn content | A sound sequence in a code review: 1. Measure first, with Instruments, so the change is justified by numbers. 2. If elements need no individual interaction, move them into a `Canvas` and draw paths in one pass. 3. If elements must stay views but compositing is the cost, try `drawingGroup()` and measure again. 4. Keep accessibility whole: one label or value summarising what the drawing shows.
- Why does drawingGroup() sometimes show a placeholder instead of a view?Apple's documentation says the drawing group only includes views SwiftUI rasterizes with its own primitives: text, images, shapes and composites of them. Views composited by Core Animation, such as complex controls, web views, media players and most UIKit or AppKit views, render as a placeholder image. Keep such views outside the flattened subtree.
- Can you put a Button inside a Canvas through its symbols?It will draw, but it will not work. The `symbols:` builder renders views so that `resolveSymbol(id:)` can stamp them, and Apple's documentation says a canvas offers no interactivity or accessibility for individual elements, including symbols. Interactive controls belong in the view hierarchy, overlaid on the canvas if needed.
- Inside a GraphicsContext, what changes if you call fill before clip(to:)?The clip no longer affects that fill. A context's state changes, such as a clip or filter, apply only to drawing issued after them. To clip one group of drawing without touching the rest, copy the context (`var masked = context`), clip the copy and draw through it; both copies still draw into the same layer.
- Thousands of Shape views cost nothing because SwiftUI views are structs
- Canvas makes every element it draws accessible automatically
- drawingGroup() renders UIKit-backed views such as a map into its image
- Adding drawingGroup() to every complex view is a free speed-up
- Canvas is the right tool for a list of tappable workout rows