In UIKit, how do you draw a rounded rectangle in a custom view's draw(_:), and how do you make it redraw?
answer
- override one method, never call it
- a path type with a corner-radius initializer
- colour comes from UIColor, not the path
- invalidate, then wait for the next cycle
- contentMode default stretches the old bitmap
basics
~10 sSubclass UIView, override draw(:), build a UIBezierPath(roundedRect:cornerRadius:), set a colour with setFill() or setStroke() and call fill() or stroke(). To redraw, call setNeedsDisplay(); UIKit runs draw(:) on its next drawing cycle.
solid answer
~40 sI subclass `UIView` and override `draw(_:)`. By the time UIKit calls it, it has made a graphics context current whose origin matches the view's bounds, so I build `UIBezierPath(roundedRect:cornerRadius:)`, call `setFill()` or `setStroke()` on a `UIColor`, and call `fill()` or `stroke()` on the path; the path carries its own `lineWidth`. I inset the rect by half the line width, because a stroke is centred on the path. I never call `draw(_:)` myself: when a property such as the badge colour changes, its `didSet` calls `setNeedsDisplay()`, which only marks the view and returns, and UIKit redraws on the next cycle. If the view resizes, I set `contentMode = .redraw`, because the default `.scaleToFill` stretches the old bitmap instead.
code
swift · 25 linesimport UIKit
final class DeliveryBadgeView: UIView {
var fillColor: UIColor = .systemGreen {
didSet { setNeedsDisplay() } // ask for a redraw; never call draw(_:)
}
override init(frame: CGRect) {
super.init(frame: frame)
isOpaque = false // corners outside the path stay transparent
contentMode = .redraw // redraw on bounds change instead of stretching
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func draw(_ rect: CGRect) {
let inset = bounds.insetBy(dx: 1, dy: 1)
let path = UIBezierPath(roundedRect: inset, cornerRadius: 12)
fillColor.setFill()
path.fill()
UIColor.label.setStroke()
path.lineWidth = 2
path.stroke()
}
}go deeper
Recall the three steps: override draw(:), build a UIBezierPath, set a UIColor and fill or stroke. Say clearly that setNeedsDisplay() is how you ask for a redraw and that draw(:) is never called by hand.
Explain what UIKit prepares before draw(_:) runs: a current context whose origin matches the bounds. Mention that the stroke is centred on the path, and that isOpaque and contentMode change what the view shows.
Show judgement about whether draw(_:) is needed at all: a solid rounded badge is a layer property, while a real drawing earns the override. Bring up the cost of redrawing the whole bounds on frequent changes.
Frame custom drawing as a team choice: a few drawing views that redraw rarely are cheap, while drawing views that redraw constantly need a review. Favour stock views and layer properties first, and keep draw(_:) for what they cannot render.
## What draw(_:) is for A `UIView` normally shows content through subviews, a background colour or its layer. When none of those can produce the picture, such as a delivery-status badge with a rounded outline and a custom fill, the view subclass overrides **`draw(_:)`** and paints with Core Graphics and UIKit's drawing helpers. Apple's documentation describes the contract precisely: - The default implementation does nothing, and a direct `UIView` subclass does not need to call `super`. - Before calling it, UIKit creates and configures a graphics context and adjusts its transform so that the **origin matches the origin of the view's bounds**. Drawing in `draw(_:)` therefore uses the same top-left, y-down points as the rest of UIKit. - `UIGraphicsGetCurrentContext()` returns that context, but you should **not keep a strong reference** to it, because it can change between calls. - The `rect` parameter is the part of the bounds that needs updating; the first time it is usually the whole visible bounds. - You **never call `draw(_:)` yourself**. ## Drawing the shape `UIBezierPath` combines path geometry with the attributes used to render it. Building a rounded rectangle is one initializer, `UIBezierPath(roundedRect:cornerRadius:)`; `init(roundedRect:byRoundingCorners:cornerRadii:)` rounds only some corners. To paint it: 1. Set the colour on the context with `UIColor.setFill()` or `UIColor.setStroke()`. The path holds no colour. 2. Set the path's own drawing attributes, such as `lineWidth`, `lineCapStyle` and `lineJoinStyle`. `stroke()` uses the path's attributes, not whatever line width the context holds. 3. Call `fill()` and/or `stroke()`; both draw into the **current** context. A stroke is **centred on the path**: half of a 2-point line falls on each side. A path built on `bounds` loses the outer half of its straight edges to the view's edge, while the rounded corners, which curve inward, keep more, so the outline looks uneven. Insetting the rect by half the line width fixes it. The Core Graphics spelling of the same thing is a `CGMutablePath` added to the context with `addPath(_:)` and painted with `strokePath()` or `fillPath()`; `CGPath` itself has no drawing functions. `UIBezierPath(cgPath:)` and the `cgPath` property convert between the two. ## Asking for a redraw `setNeedsDisplay()` marks the whole bounds as needing to be redrawn and **returns immediately**. Nothing is drawn until the next drawing cycle, when UIKit updates every invalidated view. That makes the usual pattern a property observer: - a property such as `fillColor` has a `didSet` that calls `setNeedsDisplay()`; - several changes before the next cycle lead to one redraw, not one per change; - `setNeedsDisplay(_:)` marks only a rectangle, which matters for large views (the signature-pad case). Apple's documentation adds that you should request a redraw only when the **content or appearance** changes. A geometry change alone usually does not redraw: the existing bitmap is adjusted according to `contentMode`. ## Opaque views, contentMode and resizing Two `UIView` properties change what a drawing view shows: | Property | Default | What it means for draw(_:) | |---|---|---| | `isOpaque` | `true` | An opaque view must fill its whole rect; unpainted pixels give undefined results | | `clearsContextBeforeDrawing` | `true` | For non-opaque views, the rect is pre-filled with transparent pixels | | `contentMode` | `.scaleToFill` | On resize the old bitmap is stretched; `.redraw` calls `setNeedsDisplay()` instead | A rounded badge leaves its corners unpainted, so it sets `isOpaque = false`. A badge that changes width with its text sets `contentMode = .redraw`, or its outline and corner radius stretch with the frame. ## When not to override draw(_:) Apple's documentation says a view that only shows a background colour, or sets its content through its layer, does not need `draw(_:)`. A solid rounded badge can be a background colour plus the layer's corner radius, which the lesson on Core Animation covers. `draw(_:)` earns its place when the picture is a real drawing: several paths, a dashed border, text laid around a shape, or a stroke the user draws. ## Common mistakes - Calling `draw(_:)` directly instead of `setNeedsDisplay()`. - Caching the `CGContext` in a property and drawing into it later. - Leaving `isOpaque` at `true` while leaving corners unpainted. - Building the path on `bounds` and stroking it, so the edges are clipped. - Expecting a resize to redraw while `contentMode` is still `.scaleToFill`.
- Why should a UIKit view not store the context from UIGraphicsGetCurrentContext() in a property?Apple's documentation says the context UIKit sets up for `draw(_:)` can change between calls, so you must not keep a strong reference to it. Fetch it inside `draw(_:)` each time, or use UIKit's helpers (`UIBezierPath.fill()`, `stroke()`, `UIColor.setFill()`), which draw into whatever context is current.
- When is a UIBezierPath the better choice than a CGMutablePath, and how do you move between them?`UIBezierPath` carries geometry plus rendering attributes such as `lineWidth` and draws itself into the current context with `stroke()` and `fill()`, which suits `draw(_:)`. `CGMutablePath` has no drawing functions: you add it to a `CGContext` with `addPath(_:)` and call `strokePath()` or `fillPath()`. `UIBezierPath(cgPath:)` wraps a Core Graphics path, and `cgPath` returns one.
- The badge's text grows and the view gets wider; why does its outline look stretched?A geometry change does not redraw by default. With `contentMode` at its default `.scaleToFill`, UIKit scales the existing bitmap to the new bounds, so the corner radius and line width stretch. Setting `contentMode = .redraw` makes a bounds change call `setNeedsDisplay()`, and `draw(_:)` paints the outline again at the new size.
- Calls draw(_:) directly to refresh the view after a property changes.
- Stores UIGraphicsGetCurrentContext() in a property and draws into it later.
- Assumes a stroke is drawn inside the path, so a bounds-sized outline is never clipped.
- Thinks an opaque view's unpainted corners show whatever lies behind the view.
- Expects a resize to rerun draw(_:) while contentMode is still scaleToFill.