创建一部分屏幕的图像?
问题描述:
我有一系列在我的应用程序屏幕的一部分上创建的子图层,并希望它将此图像保存为图像,然后显示图像,以便希望使应用程序运行得更快一些。我如何才能在这些图层中保存图像(暂时,因此无法在照片应用中访问)?如果有帮助,它们都在UIView里面。创建一部分屏幕的图像?
答
你可以,你想截图的内容:
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
答
使用UIGraphicsBeginImageContext
和相关功能,如下面(创建按钮的图像):
UIGraphicsBeginImageContext(button.frame.size);
CGContextRef theContext = UIGraphicsGetCurrentContext();
[button.layer renderInContext:theContext];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
NSData *theData = UIImagePNGRepresentation(theImage);
UIGraphicsEndImageContext();
对于工作示例(这实际上将图像保存在模拟器中),请参阅https://github.com/dermdaly/ButtonMaker。
答
我创造了这个类别:
.H
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
@interface UIView (ViewCapture)
- (UIImage*)captureView;
@end
.M
#import "UIView+ViewCapture.h"
@implementation UIView (ViewCapture)
- (UIImage*)captureView
{
CGRect rect = self.frame;
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
@end
使用方法如下:
UIImage *screenshot = [aView captureView];
编辑:
是不是CALayers默认缓存呢? – sosborn 2011-03-28 00:29:32