Skip to content

Instantly share code, notes, and snippets.

@davidahouse
Created November 19, 2020 12:35
Show Gist options
  • Save davidahouse/0dc6ca1026640460513c7f7f89a8b07a to your computer and use it in GitHub Desktop.
Save davidahouse/0dc6ca1026640460513c7f7f89a8b07a to your computer and use it in GitHub Desktop.
Capture a SwiftUI view to a UIImage
extension UIHostingController {
func capture() -> UIImage {
let size = sizeThatFits(in: UIScreen.main.bounds.size)
view.bounds.size = size
view.sizeToFit()
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let snapshotImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return snapshotImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment