Skip to content

Instantly share code, notes, and snippets.

@purpleblues
Created October 22, 2020 13:39
Show Gist options
  • Save purpleblues/aa83b0fb789783b135102a871ae6dd34 to your computer and use it in GitHub Desktop.
Save purpleblues/aa83b0fb789783b135102a871ae6dd34 to your computer and use it in GitHub Desktop.
Converting SwiftUI View to Image in Playground
/*
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