skip to content

Shapes, Drawing and Effects

Shape and Path draw vector graphics, Canvas draws many elements fast, and gradients, materials and shaders style them. Interviewers ask when to drop to Canvas or drawingGroup.

on this pageshow

explore

questions

6

In SwiftUI, how do you draw a custom shape, such as a fitness app's speed gauge arc, by conforming to the Shape protocol?

level: juniorimportance: must knowfreq 65%

answer

  1. one required method
  2. the rectangle layout hands you
  3. move, addLine, addArc on Path
  4. 0 degrees sits at 3 o'clock

basics

~10 s

Conform a struct to Shape and implement path(in:), building a Path from the CGRect SwiftUI passes in. The shape is itself a view: frame sizes it, and fill or stroke styles it.

solid answer

~40 s

`Shape` has one requirement I must write, `path(in rect: CGRect) -> Path`. SwiftUI calls it with the rectangle the shape was laid out in, so I compute every point from `rect`, such as `rect.midX` or `min(rect.width, rect.height) / 2`, and the gauge scales with whatever `frame` it gets. Inside, I build a `Path` with `move(to:)`, `addLine(to:)`, `addArc(center:radius:startAngle:endAngle:clockwise:)` and `closeSubpath()`. Because `Shape` refines `View`, the result goes straight into a body; with no modifier it is filled with the foreground style, and `stroke(_:style:)` or `fill(_:)` styles it. Angles start at 3 o'clock and, because y grows downward, increasing angles sweep clockwise on screen.

code

swift · 27 lines
swift
import SwiftUI

struct GaugeArc: Shape {
    var startAngle: Angle = .degrees(135)
    var endAngle: Angle = .degrees(405)
    var inset: CGFloat = 0    // half the stroke width keeps a stroke inside the frame

    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.addArc(
            center: CGPoint(x: rect.midX, y: rect.midY),
            radius: min(rect.width, rect.height) / 2 - inset,
            startAngle: startAngle,
            endAngle: endAngle,
            clockwise: false
        )
        return path
    }
}

struct SpeedGauge: View {
    var body: some View {
        GaugeArc(inset: 6)
            .stroke(.orange, style: StrokeStyle(lineWidth: 12, lineCap: .round))
            .frame(width: 160, height: 160)
    }
}

go deeper

for a junior

Recall the single requirement, path(in:), and that every point should come from the rect parameter. Know that a shape is already a view and is filled with the foreground style by default.

for a middle

Explain how Path commands build subpaths, why 0 degrees is 3 o'clock, and why clockwise: false looks clockwise on screen in SwiftUI's y-down space.

for a senior

Show you design shapes that scale with any frame, keep stored properties Sendable, and choose between a Shape type and a fixed Path for reuse across a design system.

for a principal

Frame custom shapes as design-system assets: when a bespoke outline earns a reusable type, who owns its geometry, and how it stays consistent across screens and sizes.

## The Shape protocol A **shape** in SwiftUI is any type that conforms to `Shape`. The protocol has exactly one requirement you must write: `path(in rect: CGRect) -> Path`. The other requirements, such as `sizeThatFits(_:)` (iOS 16) and `layoutDirectionBehavior` (iOS 17), come with default implementations, so a minimal custom shape is a struct with one method. `Shape` refines `View`, `Animatable` and `Sendable`. Because it is a `View`, a custom shape goes straight into a `body` with no wrapper view. Because it is `Sendable`, its stored properties must be `Sendable` too, which simple values such as `Angle`, `CGFloat` and `Double` are. (Making a shape's properties animate is a separate subject, covered with custom animation.) ## The rect is the whole contract SwiftUI calls `path(in:)` with the **rectangle the shape was given by layout**. Everything you draw should be computed from it: - `rect.midX` and `rect.midY` for the centre; - `min(rect.width, rect.height) / 2` for a radius that fits either orientation; - `rect.maxY`, `rect.minX` and friends for edges. A path computed this way scales with whatever `frame` the parent offers, so the same gauge works in a small widget-sized tile and on a full-screen summary. Hard-coding numbers such as `CGPoint(x: 80, y: 80)` makes a drawing that only looks right at one size. ## Building the Path `Path` is a value type that records drawing commands. Inside `path(in:)` you create one and append to it: 1. `move(to:)` lifts the pen and starts a new subpath. 2. `addLine(to:)` draws a straight segment from the current point. 3. `addArc(center:radius:startAngle:endAngle:clockwise:)` adds a circular arc. 4. `addQuadCurve(to:control:)` and `addCurve(to:control1:control2:)` add Bézier curves. 5. `closeSubpath()` joins the last point back to the start. Convenience initializers such as `Path(ellipseIn:)` and `Path(roundedRect:cornerRadius:)` cover common outlines. A `Path` built with the closure initializer, `Path { path in … }`, is itself usable as a shape, but its coordinates are fixed numbers, so it draws at the same size wherever it is placed. ```swift import SwiftUI struct GaugeNeedle: Shape { func path(in rect: CGRect) -> Path { var path = Path() path.move(to: CGPoint(x: rect.midX, y: rect.minY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) path.closeSubpath() return path } } ``` ## Angles in a y-down space SwiftUI's coordinate space puts the origin at the **top-left** and grows `y` **downward**. Angles are measured from the positive x-axis, which is 3 o'clock. An increasing angle therefore moves from 3 o'clock toward 6 o'clock, which is clockwise to the eye. | Call | What appears on screen | |---|---| | `addArc(…startAngle: .degrees(0), endAngle: .degrees(90), clockwise: false)` | the quarter from 3 o'clock down to 6 o'clock | | the same with `clockwise: true` | the other three quarters, going up through 12 o'clock | | a gauge from 135° to 405° with `clockwise: false` | a 270° sweep from lower-left, over the top, to lower-right | This is the most common surprise when drawing a gauge: the flag names the direction in terms of increasing angle, and with `y` pointing down that direction looks clockwise. ## Styling the result A shape with no styling modifier is **filled with the current foreground style**, as Apple's documentation for `Shape` states. To control it: - `fill(_:)` paints the interior with any `ShapeStyle` (a colour, gradient or material); - `stroke(_:lineWidth:)` and `stroke(_:style:)` trace the outline; - `frame(width:height:)` decides the rectangle `path(in:)` receives. An open path, like a gauge arc, is normally stroked; filling it fills the region between the arc and the straight line that would close it. ## Reach for built-in shapes first Before writing `path(in:)`, check whether a built-in shape or a combination already fits: - `Rectangle`, `RoundedRectangle`, `Capsule`, `Circle` and `Ellipse` cover most outlines, and static members such as `.rect(cornerRadius:)`, `.circle` and `.capsule` spell them inline wherever a shape is expected. - `UnevenRoundedRectangle` (iOS 16) gives each corner its own radius. - Since iOS 17, `Shape` and `Path` offer boolean operations such as `union(_:eoFill:)`, `subtracting(_:eoFill:)` and `intersection(_:eoFill:)`, so a cut-out can come from two simple shapes instead of hand-computed curves. A custom type earns its place when the geometry is genuinely new, like a gauge with a gap at the bottom, or when several screens must share one outline. ## Common mistakes - Using constants instead of `rect`, so the shape breaks on another device size. - Assuming 0° is 12 o'clock; it is 3 o'clock, and a gauge or ring needs a rotation or adjusted angles. - Wrapping a shape in a custom `View` just to display it; the shape already is one. - Forgetting that a stroke is centred on the path, so a thick line drawn at the full radius reaches outside the frame; insetting the radius by half the line width keeps it inside.

  • Why does addArc with clockwise: false draw an arc that looks clockwise?
    SwiftUI's origin is the top-left and `y` grows downward. Angles are measured from 3 o'clock, so an increasing angle moves down toward 6 o'clock, which the eye reads as clockwise. `clockwise: false` sweeps in the direction of increasing angle, so 0° to 90° gives the short quarter from 3 to 6 o'clock; `clockwise: true` takes the 270° route through 12 o'clock.
  • When is a bare Path enough, and when do you need a Shape type?
    A `Path { path in … }` is itself a shape, but its points are fixed numbers, so it draws at one size wherever it is placed. That suits a small decoration with known dimensions. A `Shape` type recomputes its path from the `rect` on each layout, so it adapts to different frames and devices, which is why a reusable gauge or badge outline belongs in a `Shape`.

  • path(in:) should use fixed point coordinates for a precise design
  • A Shape must be wrapped in a custom View before it can appear in a body
  • Angle zero points to 12 o'clock in a SwiftUI path
  • clockwise: true is the flag that draws a visually clockwise arc
  • A shape with no fill or stroke modifier draws nothing
open as a page

In SwiftUI, why does a thick stroke on a Circle spill past its frame, and how do strokeBorder, trim and StrokeStyle build an activity ring?

level: middleimportance: must knowfreq 60%

basics

~20 s

stroke centres its line on the path, so half the width falls outside the frame; strokeBorder insets first and stays inside. A ring adds trim(from:to:) for progress and a round-capped StrokeStyle, insetting by hand because trim drops strokeBorder.

open as a page

In SwiftUI, how do you put a frosted Material card over a workout photo, and when do you use clipShape versus mask?

level: middleimportance: should knowfreq 50%

basics

~20 s

Back the card with a Material, as in background(.ultraThinMaterial, in: .rect(cornerRadius: 16)), so it blurs the photo behind it. clipShape cuts a view to a shape's outline; mask applies another view's alpha, so it can fade.

open as a page

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?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Thousands 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.

open as a page

How far should a SwiftUI app adopt Liquid Glass and custom effects in its own components, versus system controls, when it still deploys back to iOS 17?

level: principalimportance: should knowfreq 40%

basics

~20 s

Let system controls carry Liquid Glass, which standard SwiftUI components already use, and keep glassEffect to a short list of custom floating controls behind #available with a Material fallback. Check every custom surface for legibility and under accessibility settings.

open as a page

In SwiftUI on iOS 17 and later, how do colorEffect, distortionEffect and layerEffect apply a Metal shader, and why does layerEffect need maxSampleOffset?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Each modifier runs a [[ stitchable ]] Metal function from a ShaderLibrary per pixel: colorEffect recolours one pixel, distortionEffect returns where to read from, layerEffect samples the rasterized view freely. maxSampleOffset declares how far reads may stray from each pixel.

open as a page