如何将 macOS SwiftUI 视图转换为图像?

How can you turn a macOS SwiftUI view into an image?

我知道您可以按照 these 步骤将 IOS SwiftUI 视图转换为图像,但这在 SwiftUI 扩展中使用了 UIKit 东西,而您不能在 macOS SwiftUI 中使用。 有谁知道如何 snapshot/screenshot macOS SwiftUI 视图?

在 macOS 中可以使用相同的方法。 NSHostingController 类似于 UIHostingController。另外要绘制它,应将视图添加到一些 window:

extension View {
    func snapshot() -> NSImage? {
        let controller = NSHostingController(rootView: self)
        let targetSize = controller.view.intrinsicContentSize
        let contentRect = NSRect(origin: .zero, size: targetSize)
        
        let window = NSWindow(
            contentRect: contentRect,
            styleMask: [.borderless],
            backing: .buffered,
            defer: false
        )
        window.contentView = controller.view
        
        guard
            let bitmapRep = controller.view.bitmapImageRepForCachingDisplay(in: contentRect)
        else { return nil }
        
        controller.view.cacheDisplay(in: contentRect, to: bitmapRep)
        let image = NSImage(size: bitmapRep.size)
        image.addRepresentation(bitmapRep)
        return image
    }
}