iPhone:如何将视图保存为图像? (ex.save你画的)

我发现一些示例是教你如何在iphone上画画

但它不说如何保存视图为图像?

有没有人有想法?

或者任何样品都会有帮助:)

实际上,我试图将用户的签名保存为图片并上传到服务器。

谢谢

韦伯

UIView *view = // your view UIGraphicsBeginImageContext(view.bounds.size); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

这给你可以存储使用的图像 –

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

path是你想要保存的位置。

这是一个将任何UIView渲染为图像的快速方法。 它考虑到设备运行的iOS版本,并利用获取UIView的图像表示的相关方法。

更具体地说,现在有更好的方法(即drawViewHierarchyInRect:afterScreenUpdates :)在iOS 7或更高版本上运行的设备上截取UIView的截图,也就是从我读过的内容中,被认为是一种更高效的方式比较“renderInContext”方法。

更多信息在这里: https : //developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW217

使用示例:

 #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. 

码:

 #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; } 

在MonoTouch / C#中作为扩展方法:

 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(); } }