我知道您可以通过遵循these步骤将IOS SwiftUI视图转换为镜像,但这使用了SwiftUI扩展中的UIKit内容,而您不能在macOS SwiftUI中使用它。有人知道如何对macOS SwiftUI视图进行快照/截图吗?
发布于 2021-08-30 18:17:50
在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
}
}https://stackoverflow.com/questions/68983790
复制相似问题