Updated for Xcode 12.5
SwiftUI’s views don’t have built-in function to render a view as an image, but we can write one ourselves in very little time. The key here is to wrap the view using UIHostingController
, then render its view hierarchy into a UIGraphicsImageRenderer
.
This is best done using an extension on View
, so you can call it naturally. This should wrap the view in a hosting controller, adjust the size of the hosting controller’s view to be the intrinsic content size of the SwiftUI view, clear any background color to keep the rendered image clean, then render the view into an image and send it back.
Here’s how that looks in code:
extension View {
func snapshot() -> 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 renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
To use that extension in SwiftUI, you should create your view as a property so you can reference it on demand – for example, in response to a button action.
For example, this renders a styled text view to an image, then saves it to the user’s photo album:
struct ContentView: View {
var textView: some View {
Text("Hello, SwiftUI")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.clipShape(Capsule())
}
var body: some View {
VStack {
textView
Button("Save to image") {
let image = textView.snapshot()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
}
}
Important: In order to call UIImageWriteToSavedPhotosAlbum()
you must add the NSPhotoLibraryAddUsageDescription key to your Info.plist and explain to the user why you want to write images. If you fail to do this your app will crash when you attempt to write out the image.
SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.