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

Wil*_*D47 3 macos screenshot nsimage swift swiftui

我知道您可以View按照以下步骤将 iOS SwiftUI 转换为图像,但这会使用 SwiftUI 扩展中的 UIKit 内容,而您无法在 macOS 的 SwiftUI 中使用这些内容。

有谁知道如何对 macOS SwiftUI 视图进行快照/屏幕截图?

Phi*_*hov 7

在 macOS 中可以使用相同的方法。NSHostingController是 的模拟UIHostingController。另外,为了绘制视图,应该将视图添加到某个窗口中:

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
    }
}
Run Code Online (Sandbox Code Playgroud)