和之前的iOS 关于图片的操作类似,都是通过位图上下文操作的,言归正传.
1、开启位图上下文
//因为是截取整个屏幕,就不需要设置透明度,只需要设置尺寸大小。
UIGraphicsBeginImageContext(self.view.bounds.size);
2、将当前控制器的view渲染到位图上下文中
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
3、从位图上下文获取图片
UIImage *captureImg = UIGraphicsGetImageFromCurrentImageContext();
4、结束位图编辑
UIGraphicsEndImageContext();
5、保存到沙盒当中
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [doc stringByAppendingPathComponent:@"capture.png"];
NSLog(@"path %@", path);
NSData *imageData = UIImagePNGRepresentation(captureImg);
[imageData writeToFile:path atomically:YES];
6、为了测试查看可以存放到本地桌面
NSData *imgData =UIImagePNGRepresentation(captureImg);
[imgData writeToFile:@"/Users/apple/Desktop/capture.png" atomically:YES];
代码附上:
//开启位图上下文
UIGraphicsBeginImageContext(self.view.bounds.size);
//当前控制器的view渲染在位图上下文
//render 渲染
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//获取图片
UIImage *captureImg = UIGraphicsGetImageFromCurrentImageContext();
//结束位图
UIGraphicsEndImageContext();
//保存在沙盒当中
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [doc stringByAppendingPathComponent:@"capture.png"];
NSLog(@"path %@", path);
NSData *imageData = UIImagePNGRepresentation(captureImg);
[imageData writeToFile:path atomically:YES];
//保存当前图片
NSData *imgData =UIImagePNGRepresentation(captureImg);
[imgData writeToFile:@"/Users/apple/Desktop/capture.png" atomically:YES];
网友评论