I'm wondering if anyone has figured out how to convert a SwiftUI View into an image?
I've tried encapsulating a SwiftUI View into a UIHostingController and using the following code:
import SwiftUI extension UIView { func image() -> UIImage { let renderer = UIGraphicsImageRenderer(size: self.bounds.size) let image = renderer.image { context in self.drawHierarchy(in: self.bounds, afterScreenUpdates: true) } return image } } extension UIHostingController { func image() -> Image? { guard let view = self.view else { return nil } let image = view.image() return Image(uiImage: image) } } struct RasterizedView<Content: View>: View { var controller: UIHostingController<Content> init(_ content: Content) { self.controller = UIHostingController(rootView: content) } var body: some View { controller.image() } } #if DEBUG struct RasterizedViewTest_Previews: PreviewProvider { static var previews: some View { RasterizedView(Text("TEST")) } } #endif
This code displays nothing. I went into the debugger and looked at the UIHostingController. The view always has width of 0 and a height of 0.
I forced the view to load by adding self.loadView() as a first step in UIHostingController.image(), which results in the view having a non-zero size. However, I encountered a new problem: during runtime I receive an error that looks like this:
2019-08-17 17:41:08.737684-0400 Form[88020:27394836] [Snapshotting] View (0x7feb3200a420, UIView) drawing with afterScreenUpdates:YES inside CoreAnimation commit is not supported.
Does anyone have any experience or advice that might help me solve this problem?