SwiftUI: How to take screenshot of ScrollView Content?

extension View {    
func takeScreenshot(origin: CGPoint, size: CGSize) -> UIImage {
let window = UIWindow(frame: CGRect(origin: origin, size: size))
let hosting = UIHostingController(rootView: self)
hosting.view.frame = window.frame
window.addSubview(hosting.view)
window.makeKeyAndVisible()
return hosting.view.screenShot
}
}
extension UIView {   
var screenShot: UIImage {
let rect = self.bounds
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context: CGContext = UIGraphicsGetCurrentContext()!
self.layer.render(in: context)
let capturedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return capturedImage
}
}
GeometryReader { proxy in           
VStack {
Button(action: {
let image = self.takeScreenshot(origin: proxy.frame(in: .global).origin, size: proxy.size)
print(image) //save your image here
}) {
RoundedRectangle(cornerRadius: 20)
.fill(self.color)
.overlay(
VStack {
Text("size: \(proxy.size.debugDescription)")
.foregroundColor(.white)
})
}
}
}.frame(height: 100)

iOS Developer | Swift | Flutter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store