In Core Graphics, how do you fill a rounded route-summary header with a CGGradient, and why wrap the clip in saveGState() and restoreGState()?
answer
- gradients paint a region, not a path
- clip first, then draw the gradient
- the clip lives in the graphics state
- save before the clip, restore after
- two options extend past start and end
basics
~20 sClip the context to the rounded path, then call drawLinearGradient(_:start:end:options:), which fills the whole current clip. The clip is part of the graphics state and only shrinks, so saveGState() before it and restoreGState() after let later drawing use the full view again.
solid answer
~40 sA `CGGradient` has no shape: `drawLinearGradient(_:start:end:options:)` fills the context's **current clipping region**, so with no clip it paints the whole view. I build the header's `UIBezierPath(roundedRect:cornerRadius:)` and call `addClip()`, which intersects it with the current clip, then draw the gradient from the top edge to the bottom edge. Each clip call only narrows the paintable area, and the clip is part of the graphics state, so I call `saveGState()` before clipping and `restoreGState()` after the gradient; the border stroke and any text afterwards draw unclipped. The options `drawsBeforeStartLocation` and `drawsAfterEndLocation` extend the first and last colours past the start and end points; without them, the region beyond those points stays unpainted. I create the gradient once, not in every `draw(_:)`.
code
swift · 25 linesimport UIKit
final class RouteHeaderView: UIView {
private let gradient = CGGradient(
colorsSpace: CGColorSpaceCreateDeviceRGB(),
colors: [UIColor.systemTeal.cgColor, UIColor.systemBlue.cgColor] as CFArray,
locations: [0, 1])!
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
let card = UIBezierPath(roundedRect: bounds.insetBy(dx: 8, dy: 8), cornerRadius: 16)
ctx.saveGState() // the clip is graphics state
card.addClip() // gradient now fills only the card
ctx.drawLinearGradient(gradient,
start: CGPoint(x: bounds.midX, y: bounds.minY),
end: CGPoint(x: bounds.midX, y: bounds.maxY),
options: [])
ctx.restoreGState() // clip gone again
UIColor.white.withAlphaComponent(0.6).setStroke()
card.lineWidth = 1
card.stroke() // border is not clipped to the inside
}
}go deeper
Remember that a gradient has no shape of its own and fills whatever area the clip allows. Name saveGState() and restoreGState() as the pair that scopes a clip.
Explain what the graphics state holds, from the CTM and clip to colours and shadow, and that the current path is not in it. Show why each clip call only narrows the area, so restoring the state is how you undo it.
Read a drawing routine and spot unbalanced saves, a stroke clipped by a lingering clip, or a gradient rebuilt on every redraw. Use defer to keep the stack balanced across early exits.
Decide when gradient fills belong in a shared drawing pass versus a separate layer. Weigh redraw cost against how often the view changes, and keep one documented pattern for scoped state.
## Gradients fill the clip A delivery-driver app draws a teal-to-blue gradient behind its route summary, inside a card with rounded corners. The gradient is a **`CGGradient`**: a set of colours at locations from 0 to 1 in a colour space. It has no geometry of its own. The `CGContext` header describes `drawLinearGradient(_:start:end:options:)` as **filling the current clipping region** with colours that vary along the line from the start point to the end point. Location 0 maps to the start point, location 1 to the end point, and colours are interpolated between them. So the shape of a gradient fill comes entirely from the clip. Without one, the gradient covers everything the context can paint, which in `draw(_:)` is the whole view. ## Building the gradient `CGGradient(colorsSpace:colors:locations:)` takes: - a colour space, into which each colour is converted; - an array of `CGColor` values; - an optional array of locations. With `nil`, the first colour sits at 0, the last at 1, and the rest at equal intervals. The gradient is immutable and independent of any context, so create it once, as a stored property, rather than on every redraw. ## Clipping and the graphics state Each `CGContext` keeps a **stack of graphics states**. Apple's documentation lists what `saveGState()` pushes, including: - the current transformation matrix (CTM); - the **clip region**; - line width, cap, join, miter limit and dash; - fill and stroke colours and colour spaces, and alpha; - shadow parameters and the blend mode. It also states what it does **not** save: the **current path** is not part of the graphics state. Clipping works like this: 1. `UIBezierPath.addClip()`, or `CGContext.clip(using:)` on a path added to the context, intersects the shape with the current clip. The result becomes the new clip. 2. `clip(using:)` then clears the context's current path. 3. Because each clip is an intersection, a clip call can only shrink the paintable area. Apple's documentation says that to re-enlarge it you must **save the graphics state before you clip and restore it after** the clipped drawing. The pattern is therefore `saveGState()`, clip, gradient, `restoreGState()`. Afterwards the clip is back to the full view, so the header's border stroke and title text draw normally. A `defer { ctx.restoreGState() }` placed right after the save keeps the pair balanced when the drawing code has early exits. ## The drawing options | Option | Effect | |---|---| | `[]` | Paints only between the start and end points | | `.drawsBeforeStartLocation` | Extends the colour at location 0 before the start point | | `.drawsAfterEndLocation` | Extends the colour at location 1 past the end point | When the start and end points sit on the clip's top and bottom edges, the empty option set is enough. If the gradient should finish two-thirds of the way down a taller card, `.drawsAfterEndLocation` paints the rest with the end colour instead of leaving it empty. `drawRadialGradient(_:startCenter:startRadius:endCenter:endRadius:options:)` works the same way between two circles, again filling the current clip. ## Order of operations in draw(_:) 1. Fetch the context with `UIGraphicsGetCurrentContext()`. 2. Build the rounded path once for this pass. 3. Save, clip, draw the gradient, restore. 4. Stroke the border with the same path, unclipped, so the whole line width shows. 5. Draw the title text. Stroking the border while the clip is still active would cut off the outer half of the line, because a stroke is centred on the path. ## Alternatives and limits A plain rectangular gradient that never changes could also be a gradient layer, which the lesson on Core Animation covers; Core Graphics is the right tool when the gradient shares a drawing pass with other paths and text. In SwiftUI the equivalent lives in the lesson on shapes and gradients. Common mistakes: - Drawing the gradient and expecting it to follow the last path that was filled. - Clipping without saving first, so every later drawing call is clipped too. - Expecting `saveGState()` to preserve a half-built path. - Recreating the `CGGradient` on every redraw.
- After clipping, the code calls saveGState() a second time but restores only once; what goes wrong?Each `restoreGState()` pops one state off the stack. With two saves and one restore, the state from after the first save, including the rounded clip, stays current, so the border and title draw clipped. Keep saves and restores paired, ideally with `defer` right after each save.
- How would you add a soft shadow under the gradient card without the shadow leaking onto the title text?Shadow parameters are part of the graphics state. Inside a `saveGState()`/`restoreGState()` pair, call `setShadow(offset:blur:color:)`, fill the card path with a solid colour so the shadow has a shape to follow, then restore. The gradient and text drawn after the restore carry no shadow.
Clipping is masking tape on a wall before spray painting: the spray (the gradient) covers everything you did not tape off, and saving and restoring the graphics state is laying the tape and peeling it off before you paint the trim.
- Thinks drawLinearGradient paints only inside the most recently added path.
- Believes a later clip call can enlarge the clipping area again.
- Expects saveGState() to preserve the current path being built.
- Strokes the border while the rounded clip is still active.
- Assumes the gradient options are needed to paint between start and end.