Skip to content

Instantly share code, notes, and snippets.

@zac
Created April 1, 2020 23:53
Show Gist options
  • Save zac/547763a7477f570bedc0aac92a95452d to your computer and use it in GitHub Desktop.
Save zac/547763a7477f570bedc0aac92a95452d to your computer and use it in GitHub Desktop.
enum GenerationError: Error {
case couldNotGetImageRep
case couldNotGeneratePNG
}
extension View {
/// Generates an image from the current View
/// - Parameter size: The size of the image to generate
func generateImageData(size: CGSize) throws -> Data {
let wrapper = NSHostingView(rootView: self)
wrapper.frame = CGRect(origin: .zero, size: size)
let frame = CGRect(origin: .zero, size: wrapper.convertFromBacking(wrapper.bounds.size))
guard let bitmapRepresentation = wrapper.bitmapImageRepForCachingDisplay(in: frame) else {
throw GenerationError.couldNotGetImageRep
}
bitmapRepresentation.size = wrapper.bounds.size
wrapper.cacheDisplay(in: wrapper.bounds, to: bitmapRepresentation)
guard let data = bitmapRepresentation.representation(using: .png, properties: [:]) else {
throw GenerationError.couldNotGeneratePNG
}
return data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment