实现截屏功能,其实很简单,只需要几个步骤即可。
1、创建一个bitmap上下文
2、将所需要的视图(截屏的区域)绘制到上下文中。
3、从上下文中取出图片或保存到系统相册中。
以后可能有用到这个截图方法,所以写成一个UIImage的类目,以后直接使用UIImage调用,只需要传入一个view参数(截屏的区域)就能返回截屏出来的图片对象。
<span style="font-size:18px;">@implementation UIImage (CaptureImage)
+ (UIImage *)captureView:(UIView *)view
{
UIGraphicsBeginImageContext(view.frame.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
return newImage;
}
@end
</span>
<span style="font-size:18px;"> UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
});</span>
上面参数中有一个目标方法,image:didFinishSavingWithError:contextInfo:,这里的@selector方法是系统定义好的,如果自己写一个方法是会报错的。
方法如下,针对成功和失败里面写上自己的操作即可。
<span style="font-size:18px;">- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if (error) {
NSLog(@"保存到系统相册失败,请确认相关权限");
}else{
NSLog(@"保存成功");
}
}</span>