views:

110

answers:

1

What is the easiest way to save UIView's representation to file?

My solution is,

 UIGraphicsBeginImageContext(someView.frame.size);
 [someView drawRect:someView.frame];
 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 NSString* pathToCreate = @"sample.png";

 NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
 [imageData writeToFile:pathToCreate atomically:YES];

but it seems tricky, and I think there must be more efficient way to do this.

+2  A: 

You can also use the layer like this:

UIGraphicsBeginImageContext(someView.bounds.size);
[someView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Michael Kessler
I see. It seems better than mine. :)
fish potato
And if you want double-resolution on iPhone 4, use UIGraphicsBeginImageContextWithOptions
Mike Weller