With UIGraphicsImageRenderer, how do you stamp a captured signature onto a delivery receipt photo, and what does the format's scale decide?
answer
- a renderer plus a drawing closure
- the closure's context exposes cgContext
- points times scale equals pixels
- about four bytes per pixel
- iOS 10 replacement for the begin/end functions
basics
~20 sCreate a UIGraphicsImageRenderer with the receipt's size and a format, then call image(actions:): draw the photo, then stroke the signature path. The format's scale sets how many pixels each point becomes, which fixes the image's resolution and memory.
solid answer
~40 sI make a `UIGraphicsImageRendererFormat`, set `scale` to the receipt photo's own `scale` and `opaque` to `true`, and create `UIGraphicsImageRenderer(size:format:)` with the photo's size. Inside `image(actions:)` the renderer has made its context current, so I draw the photo with `draw(in:)`, then translate the `cgContext` to the signature box and stroke the `UIBezierPath`. `pngData(actions:)` or `jpegData(withCompressionQuality:actions:)` give upload-ready data instead of a `UIImage`. The scale matters because pixel size is point size times scale: the preferred format uses the main screen's scale, so a scale-1 photo comes out three times wider and nine times larger in memory on a 3x phone. The renderer is the iOS 10 replacement that UIKit's header names for `UIGraphicsBeginImageContextWithOptions`, which is marked to be deprecated.
code
swift · 21 linesimport UIKit
func stampSignature(on receipt: UIImage, signature: UIBezierPath, in box: CGRect) -> UIImage {
let format = UIGraphicsImageRendererFormat.preferred()
format.scale = receipt.scale // match the photo, not the screen
format.opaque = true // a photo has no transparent pixels
let renderer = UIGraphicsImageRenderer(size: receipt.size, format: format)
return renderer.image { context in
receipt.draw(in: CGRect(origin: .zero, size: receipt.size))
let cg = context.cgContext
cg.saveGState()
cg.translateBy(x: box.minX, y: box.minY)
let ink = UIBezierPath(cgPath: signature.cgPath) // leave the caller's path alone
ink.lineWidth = 3
ink.lineCapStyle = .round
ink.lineJoinStyle = .round
UIColor.systemBlue.setStroke()
ink.stroke()
cg.restoreGState()
}
}go deeper
Know the shape of the call: a UIGraphicsImageRenderer with a size, then image(actions:) with drawing code inside. Mention that UIKit drawing calls in the closure draw into the renderer's context.
Explain the format: scale turns points into pixels, opaque drops transparency, preferredRange picks the colour range. Work out a bitmap's memory from its pixel size and about four bytes per pixel.
Catch the scale trap on a photo-sized canvas and reuse renderers across a batch. Say the old begin/end image context is superseded, not deprecated, and why the renderer is still the better default.
Set a team rule for offscreen bitmaps: renderers only, explicit scale for anything photo-sized, and a memory estimate in review for large canvases. The cost is a few lines per call site and a check reviewers can read.
## The job A delivery-driver app captures the customer's signature as a path on screen and must produce one proof-of-delivery image: the receipt photo with the signature stamped in a box near the bottom. That is offscreen bitmap drawing, and UIKit's tool for it is **`UIGraphicsImageRenderer`**, available since iOS 10. ## How the renderer works 1. Optionally create a **`UIGraphicsImageRendererFormat`** to change the defaults. `UIGraphicsImageRendererFormat.preferred()` (iOS 11) or `default()` gives a format suited to the main screen. 2. Create the renderer with `init(size:)`, `init(size:format:)` or `init(bounds:format:)`. The format is copied, so one format object can configure several renderers. 3. Call a rendering method with a drawing closure: - `image(actions:)` returns a `UIImage`; - `pngData(actions:)` and `jpegData(withCompressionQuality:actions:)` return encoded `Data`. 4. Inside the closure, the renderer has created a Core Graphics context with the format's attributes and made it current, so `UIImage.draw(in:)`, `UIBezierPath.stroke()` and `UIColor.setStroke()` draw into it. The closure's `UIGraphicsImageRendererContext` exposes `cgContext` for Core Graphics calls, `fill(_:)` and `stroke(_:)` helpers with optional blend modes, and `currentImage`, a snapshot of what has been drawn so far. Apple's documentation notes that a renderer **keeps a cache of contexts**, so reusing one renderer for many images of the same configuration can be cheaper than creating a new one each time. The header adds one edge: a zero width or height returns an **empty** `UIImage`, not `nil`. ## What the format controls | Property | Default in the preferred format | Effect | |---|---|---| | `scale` | The main screen's scale | Pixels per point in the output | | `opaque` | `false` | `true` promises a fully opaque bitmap; set it only when every pixel is painted | | `preferredRange` (iOS 12) | Automatic | `.standard`, `.extended` or `.automatic` colour range | | `supportsHighDynamicRange` (iOS 17) | Read-only | Reports whether the format can render HDR | `prefersExtendedRange` was the iOS 10 property; it is deprecated since iOS 12 in favour of `preferredRange`. ## Why the scale decides memory The output bitmap is **size in points × scale** in each direction. A standard-range 8-bit RGBA bitmap uses about **4 bytes per pixel**, and Core Graphics may pad each row, so the decoded size is at least width × height × 4. - A receipt `UIImage` of 3024 × 4032 points at scale 1 is 3024 × 4032 pixels, about 49 MB decoded. - Rendered with the preferred format on a 3x phone, the same size becomes 9072 × 12096 pixels, about 439 MB, for no visible gain. Setting `format.scale = receipt.scale` keeps the stamp at the photo's own resolution. For a thumbnail, the opposite applies: a small point size at screen scale is the goal. How a feed downsamples many images is the system design material on image loading; here the point is that one renderer call can allocate a very large bitmap. ## Drawing the stamp The snippet draws the photo first, then saves the graphics state, translates to the signature box, strokes a copy of the path with round caps and joins, and restores the state so later drawing is not offset. Copying through `UIBezierPath(cgPath:)` leaves the caller's path untouched. The context is UIKit's, so its origin is top-left and `UIImage.draw(in:)` draws the photo upright. In Swift, `UIGraphicsImageRenderer` is not isolated to the main actor, so a function like this can run in a background task once the inputs are captured. ## The functions it replaces Before iOS 10, the pattern was `UIGraphicsBeginImageContextWithOptions(_:_:_:)`, drawing, `UIGraphicsGetImageFromCurrentImageContext()` and `UIGraphicsEndImageContext()`. In the iOS 27.1 SDK those functions are marked **API_TO_BE_DEPRECATED** with messages naming `UIGraphicsImageRenderer` and `UIGraphicsImageRendererContext.currentImage` as replacements: superseded, not yet deprecated. The renderer removes the begin/end pairing that leaked a context when an early return skipped the end call, and it chooses wide colour automatically. ## Mistakes to avoid - Leaving the default screen scale when the input size is already in pixels. - Creating a new renderer for every thumbnail in a loop instead of reusing one. - Mutating the caller's signature path's attributes inside the closure. - Translating the context without `saveGState()` and `restoreGState()`.
- The app needs a 120-point thumbnail of each stamped receipt for a list; what changes in the renderer setup?Create one renderer with the thumbnail's point size and the preferred format, so `scale` matches the screen, and reuse it for every receipt, since Apple's documentation says renderers cache their contexts. Draw the receipt with `draw(in:)` into the aspect-fitted rect. The output is then about 360 pixels wide on a 3x phone instead of the photo's thousands.
- When does setting the format's opaque to true help, and when does it hurt?It helps when every pixel is painted, as with a full receipt photo: the renderer can produce an image without meaningful alpha, which composites more cheaply. It hurts when parts of the canvas stay unpainted, such as a signature-only image meant to overlay something else: those areas no longer come out transparent and typically render black.
- Why does a reviewer ask you to replace UIGraphicsBeginImageContextWithOptions in an old helper if it still compiles without warnings?UIKit's header marks it to be deprecated with a message naming `UIGraphicsImageRenderer` as the replacement, so it will be deprecated in a later SDK. The renderer also removes the begin/end pairing that leaks a context on an early return, picks wide colour for the device, and gives PNG or JPEG data directly.
- Says UIGraphicsBeginImageContextWithOptions is already deprecated in the current SDK.
- Thinks the renderer's size is in pixels, so scale has no effect on memory.
- Creates a new UIGraphicsImageRenderer for every image in a loop by default.
- Expects image(actions:) to return nil when the size has zero width.
- Believes prefersExtendedRange is still the way to choose the colour range.
Assumes the iOS 27.1 SDK: UIGraphicsImageRenderer is iOS 10, preferredRange iOS 12, and UIGraphicsBeginImageContextWithOptions is marked to be deprecated, not yet deprecated.