Convert SwiftUI Views Into Images — Using ImageRenderer in iOS 16
Export your views as images, take snapshots, etc
The new ImageRenderer API lets you export views as UIImage, NSImage, or CGImage. Snapshotting views or capturing RealityKit scenes just got a whole lot easier through the following function call:
ImageRenderer(content: <ViewToBeConverted>).uiImage
Let’s create a mini-poster SwiftUI app using the above concept. Here’s the code for the view that we want to convert into an image:
struct PosterView : View{ | |
@Binding var bgColor: Color | |
@Binding var text: String | |
var body: some View{ | |
ZStack { | |
Rectangle().fill($bgColor.wrappedValue.gradient) | |
.cornerRadius(20) | |
VStack { | |
Text(text) | |
.font(.largeTitle) | |
.foregroundColor(.white) | |
.minimumScaleFactor(0.5) | |
.padding() | |
Image(systemName: "swift") | |
.font(.system(size: 80)) | |
.backgroundStyle(.clear) | |
.foregroundStyle(.white) | |
.padding(20) | |
} | |
} | |
.padding() | |
} | |
} |
The PosterView
consists of a Text
and an Image
wrapped inside a Shape
.
Now, let's construct our ContentView
:
struct ContentView: View { | |
@State var exportImage: UIImage? | |
@State var bgColor = Color.blue | |
@State var text = "Hello, World!" | |
var body: some View { | |
VStack{ | |
PosterView(bgColor: $bgColor, text: $text) | |
Form{ | |
Section{ | |
TextField("Enter Title", text: $text) | |
ColorPicker("Choose a background color", selection: $bgColor).padding(.horizontal) | |
} | |
Section{ | |
Button("Export Poster"){ | |
exportImage = ImageRenderer(content: PosterView(bgColor: $bgColor, text: $text)).uiImage | |
} | |
} | |
} | |
HStack{ | |
if let exportImage{ | |
Image(uiImage: exportImage) | |
.scaledToFill() | |
} | |
} | |
} | |
} | |
} |
We’ve added a ColorPicker
and a TextField
to customize our poster’s background and text.
On tapping the Button
, we’ll get a copy of the poster view as an Image
:
To build a fully working poster app, start by wrapping the above view inside a ScrollView
.
Note: The ImageRenderer doesn’t work with all the views. Some of them, like VideoPlayer, Map are forbidden.