2011-05-21 71 views

回答

31
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是要保存到的位置。

+0

对不起,你能告诉更多的细节这段代码...我有不知道使用它... – 2011-05-21 04:37:49

+3

这个想法是为视图生成一个'UIImage'对象,所以t我们可以将它保存为图像。为此,我们使用了一些“Core Graphics”。我们将视图的图层(每个视图都有一个代表视图视觉方面的图层)绘制到图像上下文中(将上下文看作绘图板)。绘图完成后,我们生成上下文的“UIImage”对象。我们使用框架函数'UIImageJPEGRepresentation(image,1.0)'将其转换为jpeg表示形式的数据。注意'1.0'是你想要的图像的质量,用'1.0'是最好的 – 2011-05-21 06:34:09

+0

一旦我们有了一个NSData对象,我们使用它的方法'writeToFile:atomically'将图像保存在所需的文件路径中。希望这是你正在寻找的。 – 2011-05-21 06:35:54

0

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

这里是使任何的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. 

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