Reputation: 185
I am currently using this very popular approach in order to capture a view for the user to share it or save it to his photo gallery:
let renderer = UIGraphicsImageRenderer(size: CGSize(width: self.viewToCapture.bounds.size.width, height: self.viewToCapture.bounds.size.height))
let image = renderer.image { ctx in
self.viewToCapture.drawHierarchy(in: self.viewToCapture.bounds, afterScreenUpdates: true)
}
But the thing is that the result of this is very unsatisfying because the image resolution of the image is not very good. Until now, I have not found another way to do it. The renderer does not have any property (or at least I know of none) that could adjust the rendered images quality.
So, I'm looking for either a modification to the way shown above or maybe another way to capture a view and have a perfectly sharp image as result. Would be glad if you could share your knowledge about that problem. Thanks in advance.
Upvotes: 3
Views: 1184
Reputation: 633
I use this extension to create an Image from a view UIGraphicsGetCurrentContext() returns a reference to the current graphics context. It doesn't create one. This is important to remember because if you view it in that light, you see that it doesn't need a size parameter because the current context is just the size the graphics context was created with.
extension UIView {
func toImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Upvotes: 2