I have the following View extension function which creates a UIImage of the SwiftUI view by putting it in a UIHostingController then using a UIGraphicsImageRenderer to render the view:
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self.ignoresSafeArea())
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)
return renderer.image { _ in
view?.drawHierarchy(
in: controller.view.bounds,
afterScreenUpdates: true
)
}
}
}
This works but it blocks the main thread completely such that any loading spinners I display on screen don't spin. How can I stop that, or is there another way of creating a snapshot that I could use that doesn't block the main thread? Thanks!