Taking screenshots of SwiftUI views on macOS (Swift 5)
import SwiftUI
extension View {
func imageRepresentation(rect: CGRect) -> NSBitmapImageRep? {
let hosting = NSHostingView(rootView: self.frame(width: rect.width, height: rect.height))
hosting.setFrameSize(rect.size)
hosting.setBoundsSize(rect.size)
hosting.layout()
hosting.layerContentsRedrawPolicy = .onSetNeedsDisplay
hosting.setNeedsDisplay(rect)
if let imageRepresentation = hosting.bitmapImageRepForCachingDisplay(in: rect) {
hosting.cacheDisplay(in: rect, to: imageRepresentation)
return imageRepresentation
}
return nil
}
func asImage(rect: CGRect) -> NSImage? {
if let cgImage = imageRepresentation(rect: rect)?.cgImage {
return NSImage(cgImage: cgImage, size: rect.size)
}
return nil
}
func asJpegData(rect: CGRect) -> Data? {
return imageRepresentation(rect: rect)?.representation(using: .jpeg, properties: [:])
}
}
Usage:
let view = AnyView(<Your View Here>)
let imageData = view.asJpegData(rect: CGRect.init(x: 0, y: 0, width: 128, height: 128))