2010-06-16 84 views
16

将UIView的表示保存到文件的最简单方法是什么?将UIView的表示保存到文件

我的解决办法是,

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

但似乎棘手,我想一定有这样做更有效的方式。

回答

24

您也可以使用这样的层:

UIGraphicsBeginImageContext(someView.bounds.size); 
[someView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
+0

我明白了。它似乎比我的好。 :) – 2010-06-16 08:39:32

+6

如果您想在iPhone 4上使用双精度分辨率,请使用UIGraphicsBeginImageContextWithOptions – 2010-06-16 08:43:23