In a UIKit signature pad that calls setNeedsDisplay() on every touch move, why does the ink lag on a large iPad, and how do you fix it?
answer
- how much of the view is invalidated
- draw(_:) runs on the main thread
- the path grows with every point
- a dirty rect instead of the bounds
- flatten finished strokes into an image
basics
~20 ssetNeedsDisplay() invalidates the whole bounds, so each touch repaints every pixel of the view and re-strokes a path that keeps growing, all on the main thread. Invalidate only the new segment with setNeedsDisplay(_:) and flatten finished strokes into a cached image.
solid answer
~40 s`setNeedsDisplay()` marks the **entire bounds**, so every frame `draw(_:)` repaints the whole backing bitmap on the main thread: a 1000 × 700-point view on a 2x iPad is 2000 × 1400 pixels, about 11 MB, per touch move. Worse, the code re-strokes one `UIBezierPath` that holds every point since the pad opened, so the cost grows with the signature. I fix both. In `touchesMoved` I call `setNeedsDisplay(_:)` with the rect around the new segment, padded by the line width; UIKit passes it to `draw(_:)` as `rect` and updates only that part. On `touchesEnded` I flatten the stroke into a cached image with `UIGraphicsImageRenderer` and clear the live path, so `draw(_:)` draws one image plus one short stroke. Coalesced touches improve the curve's fidelity, not the cost.
code
swift · 34 linesimport UIKit
final class SignaturePadView: UIView {
private var finished: UIImage? // earlier strokes, flattened once
private let live = UIBezierPath() // the stroke under the finger
private var last: CGPoint = .zero
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
last = touches.first?.location(in: self) ?? .zero
live.move(to: last)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let point = touches.first?.location(in: self) else { return }
live.addLine(to: point)
let segment = CGRect(origin: last, size: .zero).union(CGRect(origin: point, size: .zero))
last = point
setNeedsDisplay(segment.insetBy(dx: -4, dy: -4)) // only the new segment
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
finished = UIGraphicsImageRenderer(bounds: bounds).image { _ in paint() }
live.removeAllPoints() // the live path never grows past one stroke
}
override func draw(_ rect: CGRect) { paint() }
private func paint() {
finished?.draw(in: bounds)
UIColor.label.setStroke()
live.lineWidth = 3
live.stroke()
}
}go deeper
Know that setNeedsDisplay() asks for a redraw of the whole view and that setNeedsDisplay(_:) takes a rect for a part of it.
Explain the backing bitmap: points times scale per side, about four bytes per pixel, repainted on the main thread on every invalidation.
Diagnose both costs, the full-bounds invalidation and the unbounded path, and fix them with dirty rects and a flattened image. Keep fidelity, via coalesced touches, separate from cost.
Set a review rule for drawing views on high-frequency callbacks: dirty rects, bounded state and a profile before and after. Decide when a drawing view should give way to a layer-based design.
## The symptom A delivery-driver app asks the customer to sign on an iPad. The pad is a `UIView` subclass: `touchesMoved` appends a point to a `UIBezierPath` and calls `setNeedsDisplay()`, and `draw(_:)` strokes the path. On a phone it feels fine. On a large iPad, after a few seconds of signing, the ink trails the finger and the UI stutters. Two separate costs compound. ## Cost 1: the whole view is repainted `setNeedsDisplay()` marks the receiver's **entire bounds** as needing to be redrawn. On the next drawing cycle UIKit calls `draw(_:)` with that full rect, and Core Graphics repaints the view's backing bitmap: - The bitmap is the view's size in points times its scale in each direction, at about 4 bytes per pixel. - A 1000 × 700-point pad at 2x is 2000 × 1400 pixels, roughly 11 MB to clear and repaint for each move event. - `UIView` is isolated to the main actor and `draw(_:)` runs there, so this work competes with touch handling and layout in the same frame. ## Cost 2: the path never stops growing The live `UIBezierPath` holds every point since the screen opened. `stroke()` processes the whole path each time, so stroking cost rises with the number of segments. A long signature, or a pad that never clears between strokes, gets slower with every frame. Calling `setNeedsDisplay()` many times before one cycle does not queue many draws, since UIKit only notes the request; the cost is in what each draw does. ## The fixes 1. **Invalidate only what changed.** `setNeedsDisplay(_:)` marks a rectangle. Apple's documentation says `draw(_:)` receives the portion of the bounds that needs updating as `rect`, and that drawing should be limited to it. The rect around the last segment, inset by about the line width so round caps are covered, is a few hundred pixels instead of millions. 2. **Flatten finished strokes.** On `touchesEnded`, render the cached image plus the live stroke into a new image with `UIGraphicsImageRenderer(bounds:)`, store it, and clear the live path with `removeAllPoints()`. `draw(_:)` then draws one image and one short stroke, whatever the signature's length. 3. **Keep one painting routine.** The snippet's `paint()` is called by both `draw(_:)` and the renderer closure, because Apple's documentation says never to call `draw(_:)` directly. 4. **Measure.** Profiling with Instruments, covered in the lesson on Xcode, should show time in the drawing code fall after the change. | Approach | Pixels repainted per move | Stroke cost per move | |---|---|---| | `setNeedsDisplay()` + one growing path | Whole bounds | Grows with every point | | `setNeedsDisplay(_:)` + one growing path | One segment's rect | Still grows | | `setNeedsDisplay(_:)` + flattened strokes | One segment's rect | One stroke only | ## Fidelity is a separate problem Fast strokes can look jagged because touches arrive once per frame. `UIEvent.coalescedTouches(for:)` (iOS 9) returns the intermediate samples the hardware recorded, and `predictedTouches(for:)` returns predicted ones that cut perceived latency. Adding coalesced points makes the curve smoother; it does not reduce drawing cost, and it slightly increases it, which makes the dirty rect matter more. ## The same bug elsewhere The pattern is not unique to signatures. A route list whose cells call `setNeedsDisplay()` from `scrollViewDidScroll(_:)` redraws every visible cell on every scroll tick, and the stutter has the same cause. The rule is the same: redraw only when content or appearance changes, and only the part that changed. A live stroke can also be handed to a shape layer, which the render server draws; that trade is covered with Core Animation. How many milliseconds a frame allows at 60 or 120 Hz is the system design material on frame budgets. ## Review checklist - Does any high-frequency callback call `setNeedsDisplay()` without a rect? - Does `draw(_:)` limit work to `rect`, or at least rely on it being small? - Is any path or array of points unbounded across the screen's life? - Is a cached image drawn at the view's own scale, not a photo's?
- Why does the dirty rect in touchesMoved need padding by about the line width?A stroke is centred on the path and a round cap extends past the end point, so ink lands up to half the line width outside the segment's bounding box. Without padding, UIKit updates a rect that misses those pixels and the stroke edges look chopped until a full redraw.
- If draw(_:) still draws the whole cached image when only a small rect is dirty, is the dirty rect pointless?No. UIKit updates only the invalidated part of the view's content, so pixels outside it are not repainted even though the draw calls cover more. The remaining cost is processing the calls themselves; for a large cached image you can also draw only the needed portion, but the dirty rect already removes most of the work.
- When do you stop optimizing draw(_:) and move the live stroke to a shape layer instead?When the stroke must animate or redraw every frame even after dirty rects and flattening, a shape layer lets the render server rasterize the path while the main thread only updates its geometry. That trade, including its own costs, is covered with Core Animation; Core Graphics stays the tool for flattening and exporting the finished signature.
- Believes setNeedsDisplay() redraws only the part of the view that changed.
- Thinks many setNeedsDisplay() calls before a frame queue one draw each.
- Says draw(_:) runs on a background thread, so its cost never affects touches.
- Treats coalesced touches as a fix for drawing cost rather than stroke fidelity.
- Keeps one path for the whole session and never flattens finished strokes.