Created
April 1, 2020 23:53
-
-
Save zac/547763a7477f570bedc0aac92a95452d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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