[英]Export SwiftUI View as image macOS
I want to export a SwiftUI View on macOS.我想在 macOS 上导出 SwiftUI 视图。 I have code that works on iOS, but it uses UIKit.我有适用于 iOS 的代码,但它使用 UIKit。 I can't find another example to do it without UIKit.如果没有 UIKit,我找不到另一个例子来做到这一点。
Does anybody know how to do it?有人知道怎么做吗?
fileprivate extension View {
func snapshot(device: Device) -> 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 exportWidth = device.width / UIScreen.main.scale
let exportHeight = device.height / UIScreen.main.scale
let renderer = UIGraphicsImageRenderer(size: CGSize(width: exportWidth, height: exportHeight))
return renderer.image { _ in
view?.drawHierarchy(in: CGRect(x: 0, y: 0, width: exportWidth, height: exportHeight), afterScreenUpdates: true)
}
}
}
I know I can create a NSHostingController
, but I think I need some alternative for UIGraphicsImageRenderer
.我知道我可以创建一个NSHostingController
,但我认为我需要一些UIGraphicsImageRenderer
替代方案。
Thanks in advance提前致谢
In NSView there are two methods:在 NSView 中有两种方法:
func bitmapImageRepForCachingDisplay(in: NSRect) -> NSBitmapImageRep?
and和
func cacheDisplay(in: NSRect, to: NSBitmapImageRep)
Once you have the NSBitmapImageRep
, you can ask for the image in a number of formats using its:一旦你有了NSBitmapImageRep
,你就可以使用它来请求多种格式的图像:
func representation(using storageType: NSBitmapImageRep.FileType,
properties: [NSBitmapImageRep.PropertyKey : Any]) -> Data?
(the NSView to draw is the one owned by the hosting controller if that wasn't clear) (如果不清楚,要绘制的 NSView 是托管控制器所拥有的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.