iOS的截屏功能可以将当前界面中的UI元素保存成UIImage。
- (UIImage *)captureImageFromView:(UIView *)view
{
CGRect screenRect = [view bounds];
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx =UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
对于iOS7以后的系统,还可以通过系统提供的API: UIView的实例方法:
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates;来实现截屏功能。
afterUpdates参数表示是否在所有效果应用在视图上了以后再获取快照。例如,如果该参数为NO,则立马获取该视图现在状态的快照,反之,以下代码只能得到一个空白快照:
[view snapshotViewAfterScreenUpdates:YES];
[view setAlpha:0.0];
由于我们设置afterUpdates参数为YES,而视图的透明度值被设置成了0,所以方法将在该设置应用在视图上了之后才进行快照,于是乎屏幕空空如也。另外就是……你可以对快照再进行快照……继续快照……
// iOS以后的系统,还可以通过以下方法截屏,截取UIView返回UIImage
#import "UIView+SnapShot.h"
@implementation UIView (SnapShot)
- (UIImage *)snapshot
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size,YES, 0);
[selfdrawViewHierarchyInRect:self.boundsafterScreenUpdates:NO];
UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end