【问题标题】:How can you turn a macOS SwiftUI view into an image?如何将 macOS SwiftUI 视图转换为图像?
【发布时间】:2021-08-30 12:01:05
【问题描述】:

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

【问题讨论】:

  • 该链接适用于 SwiftUI
  • @loremipsum 是的,但它包括 macOS SwiftUI 无法使用的 UIKit 东西

标签: swift macos swiftui screenshot


【解决方案1】:

在 macOS 中可以使用相同的方法。 NSHostingControllerUIHostingController 的模拟。还要让它绘制视图应该添加到某个窗口:

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2019-12-03
    • 2020-06-30
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多