SwiftUI View to UIImage
While building out Pavo, an app for developers to see app analytics for their iOS/Android apps, I wanted to give the users a way to export stats from their app analytics as images they can save and then share.
It wasn’t necessarily a straightforward process as SwiftUI unlike UIKit doesn’t yet have the ability to convert any view to a UIImage.
This is the process that eventually worked for me.
The first thing I did was move everything shareable as an image into a separate reusable view. So that way, I could design it as an image as opposed to it being rendered on the screen. So setting frame sizes for different scenarios and background colors without putting too much code/logic into the already existing single app analytics view shown above.
I pass all of the @ObservedObjects at initialization so that ShareView has all it needs to render an image as fast as possible.
Next thing was to convert the SwiftUI view to a UIView by hosting in a UIHostingController. Then add the UIHostingController view as a subview of the topmost controller but at a point far off on the screen.
Then I rendered a UIImage from the UIHostingController view. Making sure to calculate my sizes properly. Here are the extensions I used for both.
Finally passing the rendered UIImage to a Share Sheet allowed users to save to their Photo Roll or just send it off to any other application they wanted.
Final Results
My hope is that as we see more of SwiftUI, a lot of this functionality would come bundled in much easier ways.