Skip to content

Instantly share code, notes, and snippets.

@michaelrockhold
Created November 22, 2024 18:37
Show Gist options
  • Select an option

  • Save michaelrockhold/4087a66313dbfa834a930e497f6c9f56 to your computer and use it in GitHub Desktop.

Select an option

Save michaelrockhold/4087a66313dbfa834a930e497f6c9f56 to your computer and use it in GitHub Desktop.
Display a CGImage that you made on the fly in a SwiftUI View
struct MyView: View {
@State var cgImage: CGImage? = nil
var imageView: Image {
if let image = cgImage {
Image(decorative: image, scale: 1.0, orientation: .up)
} else {
Image(size: CGSize(width: 640.0, height: 480.0)) { (gc: inout GraphicsContext) in
let p = Path(CGRect(x: 0, y: 0, width: 640, height: 480))
gc.fill(p, with: .color(.red))
gc.draw(Text("Hello, World"), in: CGRect(x: 0, y: 0, width: 640, height: 480))
}
}
}
var body: some View {
// la la la
self.imageView
.resizable()
.aspectRatio(contentMode: .fit)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment