首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SwiftUI视图到AppKit中的NSImage

SwiftUI视图到AppKit中的NSImage
EN

Stack Overflow用户
提问于 2021-04-25 19:35:03
回答 1查看 294关注 0票数 9

SwiftUI 2.0 # Swift 5.4 \ Xcode 12.4 \x{e76f} macOS大Sur 11.4

在iOS中,有一种方法可以将SwiftUI视图呈现给在AppKit中不工作的UIImage,只有UIKit:

代码语言:javascript
复制
extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

在AppKit上有什么办法可以解决这个问题吗?UIGraphicsImageRenderer(size:)方法不适用于AppKit,也没有等效的方法。

EN

回答 1

Stack Overflow用户

发布于 2022-02-08 23:53:44

如果我正确地理解了你的问题,你应该能够使用NSBitmapImageRef来完成这个任务!

下面是一个从NSImage视图生成SwiftUI的简单示例(注意:您的主机视图必须是可见的!):

代码语言:javascript
复制
let view = MyView() // some SwiftUI view
let host = NSHostingView(rootView: view)

// Note: the host must be visible on screen, which I am guessing you already have it that way. If not, do that here.

let bitmapRep = host.bitmapImageRepForCachingDisplay(in: host.bounds)
host.cacheDisplay(in: host.bounds, to: bitmapRep!)

let image = NSImage(size: host.frame.size)
image.addRepresentation(bitmapRep!)

下面是NSHostingView的一个扩展,可以安全地生成快照:

代码语言:javascript
复制
extension NSHostingView {
    func snapshot() -> NSImage? {
        // Make sure the view is visible:
        guard self.window != nil else { return nil }

        // Get bitmap data:
        let bitmapRep = self.bitmapImageRepForCachingDisplay(in:
        self.bounds)
        self.cacheDisplay(in: self.bounds, to: bitmapRep!)

        // Create NSImage from NSBitmapImageRep:
        let image = NSImage(size: self.frame.size)
        image.addRepresentation(bitmapRep!)
        
        return image
    }
}

我希望这能帮到你。如果你有什么问题请告诉我!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67257489

复制
相关文章

相似问题

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