首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将macOS SwiftUI视图转换为图像?

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

Stack Overflow用户
提问于 2021-08-30 12:01:05
回答 1查看 71关注 0票数 0

我知道您可以通过遵循these步骤将IOS SwiftUI视图转换为镜像,但这使用了SwiftUI扩展中的UIKit内容,而您不能在macOS SwiftUI中使用它。有人知道如何对macOS SwiftUI视图进行快照/截图吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-30 18:17:50

在macOS中也可以使用相同的方法。NSHostingController类似于UIHostingController。此外,要绘制该视图,应将其添加到某个窗口:

代码语言:javascript
复制
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
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68983790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档