Created
October 22, 2020 13:39
-
-
Save purpleblues/aa83b0fb789783b135102a871ae6dd34 to your computer and use it in GitHub Desktop.
Converting SwiftUI View to Image in Playground
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
| /* | |
| Paste it to Xcode Playground | |
| */ | |
| import SwiftUI | |
| import PlaygroundSupport | |
| extension NSView { | |
| func cachedImageRepresentation() -> NSBitmapImageRep { | |
| let imageRepresentation = | |
| bitmapImageRepForCachingDisplay(in: bounds)! | |
| cacheDisplay(in: bounds, to: imageRepresentation) | |
| return imageRepresentation | |
| } | |
| } | |
| struct ContentView: View { | |
| var body: some View { | |
| Text("Test") | |
| .frame(width: 200, height: 200) | |
| .border(Color.green) | |
| } | |
| } | |
| let view = NSHostingView(rootView: ContentView()) | |
| PlaygroundPage.current.liveView = view | |
| let outputURL = | |
| FileManager.default.temporaryDirectory.appendingPathComponent("result.png") | |
| try view.cachedImageRepresentation() | |
| .converting(to: .sRGB, renderingIntent: .default)! | |
| .representation(using: .png, properties: [:])! | |
| .write(to: outputURL) | |
| print("Saved image to \(outputURL.path)") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment