SwiftUI 2.0 # Swift 5.4 \ Xcode 12.4 \x{e76f} macOS大Sur 11.4
在iOS中,有一种方法可以将SwiftUI视图呈现给在AppKit中不工作的UIImage,只有UIKit:
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,也没有等效的方法。
发布于 2022-02-08 23:53:44
如果我正确地理解了你的问题,你应该能够使用NSBitmapImageRef来完成这个任务!
下面是一个从NSImage视图生成SwiftUI的简单示例(注意:您的主机视图必须是可见的!):
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的一个扩展,可以安全地生成快照:
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
}
}我希望这能帮到你。如果你有什么问题请告诉我!
https://stackoverflow.com/questions/67257489
复制相似问题