SwiftUI View to UIImage

Bezaleel Ashefor
3 min readDec 17, 2021

--

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.

Stats from app analytics, users can export from.

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.

ShareView Component

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.

View+asImage Extensions

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

All stats rendered from the app
All stats rendered from the app

My hope is that as we see more of SwiftUI, a lot of this functionality would come bundled in much easier ways.

--

--

Bezaleel Ashefor

Creator. I am also an iOS/macOS engineer building Viso (https://getviso.app) and Litur (https://litur.app). Sometimes I moonlight as a full stack engineer