将UIView的表示保存到文件中

fis*_*ato 16 iphone image save 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];
Run Code Online (Sandbox Code Playgroud)

但它似乎很棘手,我认为必须有更有效的方法来做到这一点.

Mic*_*ler 24

你也可以使用这样的图层:

UIGraphicsBeginImageContext(someView.bounds.size);
[someView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

  • 如果你想在iPhone 4上使用双重分辨率,请使用UIGraphicsBeginImageContextWithOptions (6认同)