2011-05-21 92 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; 
}