AboulEinein
AboulEinein

Reputation: 1101

How to save UIView content (screenshot) without reducing it's quality

I have a UIView and I want to save it's content to an image, I successfully did that using UIGraphicsBeginImageContext and UIGraphicsGetImageFromCurrentImageContext() but the problem is that the image quality is reduced. Is there a way to take a screenshot/save UIView content to an image without reducing it's quality?

Here's a snippet of my code:

UIGraphicsBeginImageContext(self.myView.frame.size);
[self.myview.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

Upvotes: 0

Views: 244

Answers (2)

Douglas Hill
Douglas Hill

Reputation: 1547

Mital Solanki’s answer is a fine solution, but the root of the problem is that your view is on a retina screen (so has a scale factor of 2) and you are creating a graphics context with a scale factor of 1. The documentation for UIGraphicsBeginImageContext states:

This function is equivalent to calling the UIGraphicsBeginImageContextWithOptions function with the opaque parameter set to NO and a scale factor of 1.0.

Instead use UIGraphicsBeginImageContextWithOptions with a scale of 0, which is equivalent to passing a scale of [[UIScreen mainScreen] scale].

Upvotes: 3

Mital Solanki
Mital Solanki

Reputation: 171

Try Following Code :

UIGraphicsBeginImageContextWithOptions(YourView.bounds.size, NO, 0);

[YourView drawViewHierarchyInRect:YourView.bounds afterScreenUpdates:YES];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

This code working Awsome...!!!

Upvotes: 4

Related Questions