SwiftUI SwiftUI Drawing and Graphics 1 — Questions and Answers
Question 1: Which protocol do you implement to create a custom SwiftUI shape?
- Drawable
- Shape (Correct answer)
- Path
- CustomShape
Correct answer: Shape
Conforming to the `Shape` protocol and implementing `path(in:)` lets you create fully custom drawable shapes.
Question 2: What type is used to construct a custom drawing path in SwiftUI's Shape protocol?
- CGPath
- BezierPath
- Path (Correct answer)
- UIBezierPath
Correct answer: Path
SwiftUI uses its own `Path` type (wrapping CGPath) in the `path(in rect: CGRect)` method required by the `Shape` protocol.
Question 3: Which modifier fills a SwiftUI Shape with a color?
- .backgroundColor()
- .foregroundColor()
- .fill()
- Both B and C work on Shape (Correct answer)
Correct answer: Both B and C work on Shape
Both `.fill()` (which applies a fill directly) and `.foregroundColor()` (which sets the shape's rendering color) can color a SwiftUI Shape.
Question 4: How do you draw only the outline of a SwiftUI Shape?
- .border()
- .stroke() (Correct answer)
- .outline()
- .path()
Correct answer: .stroke()
`.stroke()` renders only the outline of a shape with a configurable line width and style.
Question 5: Which SwiftUI type provides a canvas for immediate-mode drawing similar to Core Graphics?
- DrawingView
- Canvas (Correct answer)
- GraphicsContext
- CoreGraphicsView
Correct answer: Canvas
`Canvas` (iOS 15+) accepts a closure receiving a `GraphicsContext` and `CGSize`, enabling 2D immediate-mode drawing.
Question 6: What does the `.trim(from:to:)` modifier do on a SwiftUI Shape?
- Clips the shape to a rectangle
- Draws only a fraction of the shape's path between two normalized positions (Correct answer)
- Trims whitespace padding
- Removes corners from the shape
Correct answer: Draws only a fraction of the shape's path between two normalized positions
`.trim(from:to:)` draws the portion of the shape's path between the start and end fractions (0.0–1.0), useful for progress indicators.
Which protocol do you implement to create a custom SwiftUI shape?