In UIKit's draw(_:), why does a CGImage drawn with CGContext's draw(_:in:) come out upside down, and how do you fix it?
answer
- two coordinate systems, one context
- Quartz's origin is bottom-left
- UIKit flips the CTM to top-left
- UIImage knows its orientation, CGImage does not
- translate by height, scale y by -1
basics
~20 sQuartz's default space has its origin at the bottom-left with y up; UIKit flips its contexts to top-left with y down. CGContext's draw(_:in:) places the image in Quartz terms, so it lands upside down. Draw a UIImage instead, or flip locally.
solid answer
~40 sA raw `CGContext`, such as one made with `CGContext(data:width:height:...)`, has its origin at the **bottom-left** and y pointing up. For `draw(_:)`, the image renderer and the PDF renderer, UIKit sets the context's transform so the origin matches the view's top-left and y points down. `CGContext.draw(_:in:)` with a `CGImage` places the image's top row at the rect's maximum y in user space, which under UIKit's flip is the bottom, so the picture is upside down. The simplest fix is `UIImage(cgImage:).draw(in:)`, which draws upright and also honours `imageOrientation`; a camera photo's `cgImage` drawn raw can come out rotated as well, because the orientation lives on the `UIImage`. Otherwise I scope a flip: `saveGState()`, `translateBy(x: 0, y: rect.minY + rect.maxY)`, `scaleBy(x: 1, y: -1)`, draw, `restoreGState()`.
code
swift · 20 linesimport UIKit
final class ProofThumbnailView: UIView {
var proof: CGImage? { didSet { setNeedsDisplay() } }
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext(), let proof else { return }
let target = bounds.insetBy(dx: 4, dy: 4)
// UIKit's context is top-left with y down; a CGImage drawn as-is lands upside down.
ctx.saveGState()
ctx.translateBy(x: 0, y: target.minY + target.maxY)
ctx.scaleBy(x: 1, y: -1)
ctx.draw(proof, in: target)
ctx.restoreGState()
// Or let UIKit handle the flip:
// UIImage(cgImage: proof).draw(in: target)
}
}go deeper
Remember that Quartz and UIKit put the origin in different corners, and that drawing a UIImage avoids the problem.
Explain that the flip lives in the CTM that UIKit sets up, and show the translate-and-scale fix inside a saved graphics state.
Separate the two traps, the flipped axis and the missing orientation on a CGImage, and debug which context a snippet draws into before changing any transform.
Keep coordinate handling in one helper so feature code never hand-writes flips. Weigh the cost of shared drawing utilities against repeated one-off fixes across screens.
## Two coordinate conventions Core Graphics and UIKit disagree about which way is up. - **Quartz user space** in a raw bitmap context starts with its origin at the **bottom-left** and y increasing upward. A context made with `CGContext(data:width:height:bitsPerComponent:bytesPerRow:space:bitmapInfo:)` and no transform behaves this way: filling a 1-point-high rect at y = 0 paints the bottom row of the image. - **UIKit** uses a top-left origin with y increasing downward. Apple's documentation for `draw(_:)` says UIKit creates and configures the context and **adjusts its transform** so that the origin matches the view's bounds. The image renderer and the PDF renderer hand you contexts with the same UIKit orientation. The flip lives in the **current transformation matrix (CTM)**: UIKit's contexts carry a transform that mirrors the y axis and shifts the origin to the top. ## Why the image comes out inverted `CGContext.draw(_:in:byTiling:)` with a `CGImage` draws the image as Quartz expects: its first row at the top of the rect in a y-up space, which is the rect's maximum y. Under UIKit's flipped CTM, maximum y is the bottom of the view, so the photo appears upside down. UIKit's own drawing methods, such as `UIImage.draw(in:)` and `NSString.draw(at:withAttributes:)`, are written for UIKit's orientation and come out upright. The same mismatch runs the other way: drawing UIKit content into a raw bitmap context you created yourself, after making it current with `UIGraphicsPushContext(_:)`, puts text and images upside down unless you flip that context first. ## The fixes 1. **Draw through UIKit.** `UIImage(cgImage:).draw(in:)` draws the image upright in UIKit's coordinates. When you already have a `UIImage`, draw it directly rather than its `cgImage`. 2. **Flip locally, inside a saved state:** - `saveGState()`; - `translateBy(x: 0, y: rect.minY + rect.maxY)`; - `scaleBy(x: 1, y: -1)`; - `draw(image, in: rect)`; - `restoreGState()`. The translation maps the rect onto itself mirrored, so the same `rect` can be passed to the draw call. The restore keeps the flip from affecting anything drawn later. 3. **Never flip globally** at the top of `draw(_:)` without restoring: every UIKit call afterwards would come out inverted. ## Orientation is a second, separate trap A `CGImage` is a grid of pixels with no orientation. A `UIImage` adds `imageOrientation`, and a photo from the camera often stores its pixels in sensor order with the rotation recorded only in that property. Drawing `photo.cgImage` with `CGContext.draw` ignores the orientation, so a portrait proof-of-delivery photo can come out sideways as well as flipped. `UIImage.draw(in:)` applies the orientation. Rotating the pixels for upload is a separate step, done by rendering the `UIImage` into an image renderer. | Call | Upright in a UIKit context | Honours imageOrientation | |---|---|---| | `UIImage.draw(in:)` | Yes | Yes | | `CGContext.draw(_:in:)` with a `CGImage` | No | No (a CGImage has none) | | `CGContext.draw` inside a local flip | Yes | No | ## Where else the axis flips - **Raw bitmap contexts** you create yourself keep the bottom-left origin, so code that computes rects in UIKit terms must flip before drawing. - **PDF links.** Apple's documentation for `UIGraphicsPDFRenderer` notes that `addDestination(withName:at:)` and `setDestinationWithName(_:for:)` use the underlying PDF coordinate space, whose y-axis is flipped with respect to the coordinate system Core Graphics uses; it suggests converting with the context's `userSpaceToDeviceSpaceTransform`. - **Core Text** lays out text in Quartz's y-up space, so text drawn with it into a UIKit context needs the same flip; that detail belongs to the text layout material. ## How to debug it - Check which context the code draws into: UIKit-provided or one you created. - Read the CTM with `ctm` before drawing, or draw a small marker at y = 0 to see which edge it lands on. - Look for a `CGImage` drawn where a `UIImage` was available. The review rule that follows: in UIKit contexts, draw images through `UIImage`, and keep every manual flip inside a `saveGState()`/`restoreGState()` pair.
- Why does the translation use rect.minY + rect.maxY instead of the view's height?Scaling y by -1 mirrors around y = 0. Translating by `minY + maxY` first maps the rect onto itself mirrored, so the image fills the same target rect in either orientation. Translating by the view's height works only when the rect spans the whole view; for an inset target it shifts the image.
- A proof-of-delivery photo drawn with UIImage.draw(in:) is upright on screen, but the uploaded file is sideways in another viewer; why?The `UIImage` applied its `imageOrientation` while drawing, but the uploaded file was most likely encoded from the original pixels plus an orientation tag, which the other viewer ignores. Rendering the `UIImage` into a `UIGraphicsImageRenderer` and encoding that result bakes the rotation into the pixels.
- Says every Core Graphics context, including raw bitmap ones, has a top-left origin.
- Fixes the flip by scaling the whole context at the top of draw(_:) and never restoring.
- Believes a CGImage carries the photo's orientation like a UIImage does.
- Blames the image renderer's scale for an upside-down image.
- Thinks UIImage.draw(in:) also draws upside down in UIKit's contexts.