IPhone: how to save a view as an image ??? (for example, what you draw)

I found some sample teach you how to draw on iphone

but he doesnโ€™t say how to save the view as an image?

Has anyone got an idea ???

Or any sample will be useful :)

In fact, I am trying to save the user signature as an image and upload it to the server.

thanks

Webber

+7
source share
3 answers
UIView *view = // your view UIGraphicsBeginImageContext(view.bounds.size); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

This gives an image that you can save with -

 NSData *imageData = UIImageJPEGRepresentation(image, 1.0); [imageData writeToFile:path atomically:YES]; 

where path is the location you want to save.

+31
source

Here is a quick way to render any UIView as an image. It takes into account the version of iOS on which the device is running, and uses the appropriate method to obtain a representation of the UIView image.

In particular, there is now a better method (i.e. drawViewHierarchyInRect: afterScreenUpdates :) for taking a screenshot of a UIView on devices running iOS 7 or later, which, from what I read, is considered more compared to the renderInContext method .

Further information here: https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW217

EXAMPLE OF USE:

 #import <QuartzCore/QuartzCore.h> // don't forget to import this framework in file header. UIImage* screenshotImage = [self imageFromView:self.view]; //or any view that you want to render as an image. 

CODE:

 #define IS_OS_7_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) - (UIImage*)imageFromView:(UIView*)view { CGFloat scale = [UIScreen mainScreen].scale; UIImage *image; if (IS_OS_7_OR_LATER) { //Optimized/fast method for rendering a UIView as image on iOS 7 and later versions. UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, scale); [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } else { //For devices running on earlier iOS versions. UIGraphicsBeginImageContextWithOptions(view.bounds.size,YES, scale); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } return image; } 
+4
source

In MonoTouch / C # as an extension method:

 public static UIImage ToImage(this UIView view) { try { UIGraphics.BeginImageContext(view.ViewForBaselineLayout.Bounds.Size); view.Layer.RenderInContext(UIGraphics.GetCurrentContext()); return UIGraphics.GetImageFromCurrentImageContext(); } finally { UIGraphics.EndImageContext(); } } 
0
source

All Articles