Created
November 22, 2024 18:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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