I’m trying to create a script to take a screenshot programmatically in SwiftUI. Here’s the function I have so far:
func takeSnapshot<Content: View>(of view: Content) -> UIImage? {
var image: UIImage?
uiQueue.sync {
let controller = UIHostingController(rootView: view)
controller.view.bounds = .init(origin: .zero, size: .init(width: 200, height: 150))
let renderer = UIGraphicsImageRenderer(size: controller.view.bounds.size)
image = renderer.image { context in
controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
return image
}
/////////////////////////////////
import SwiftUI
struct ContentView: View {
@EnvironmentObject var cameraViewModel: CameraViewModel
var body: some View {
VStack {
if let image = cameraViewModel.capturedImage {
Image(uiImage: image)
.resizable()
.scaledToFit()
} else {
Text("No photo captured yet.")
.foregroundColor(.white)
}
Button(action: {
if let snapshot = cameraViewModel.takeSnapshot(of: snapshotView) {
cameraViewModel.capturedImage = snapshot
}
}) {
Text("Take Snapshot of View")
.foregroundColor(.white)
.padding()
.background(Color.green)
.cornerRadius(10)
}
}
.background(Color.black)
}
var snapshotView: some View {
// i don't know what to put in here ..???
}
}
I am not sure if this is the best approach, especially for creating a button that takes a screenshot. Any suggestions or improvements would be appreciated!