【iOS】Quartz2D截屏

本文介绍了一种在iOS应用中实现屏幕截图并保存至设备相册的方法。通过使用UIKit框架提供的API,如UIGraphicsBeginImageContext和UIGraphicsGetImageFromCurrentImageContext,结合dispatch_after进行延时截图,最后利用UIImageWriteToSavedPhotosAlbum将图片保存到相册。此外还提供了错误处理机制。

 

一、简单说明

在程序开发中,有时候需要截取屏幕上的某一块内容,比如捕鱼达人游戏。如图:

完成截屏功能的核心代码:- (void)renderInContext:(CGContextRef)ctx;调用某个view的layer的renderInContext:方法即可

 

二、代码示例

  storyboard界面搭建:

 1 - (IBAction)BtnClick:(UIButton *)sender {
 2     
 3     //延迟两秒保存
 4     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
 5         //获取图形上下文
 6         //    UIGraphicsBeginImageContext(self.view.frame.size);
 7         UIGraphicsBeginImageContext(self.contentView.frame.size);
 8         //将view绘制到图形上下文中
 9         
10         //    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
11         [self.contentView.layer renderInContext:UIGraphicsGetCurrentContext()];
12      
13         
14         //将截屏保存到相册
15         UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
16         
17         UIImageWriteToSavedPhotosAlbum(newImage,self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
18     });
19 }
20 
21  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
22 {
23     if (error) {
24         [MBProgressHUD showError:@"保存失败,请检查是否拥有相关的权限"];
25     }else
26     {
27 //        [MBProgressHUD showMessage:@"保存成功!"];
28         [MBProgressHUD showSuccess:@"保存成功!"];
29     }
30 }
View Code
 
把截取的图片保存到手机的相册中:
 
 
说明:把整个屏幕画到一张图片里
1.创建一个bitmap的上下文
2.将屏幕绘制带上下文中
3.从上下文中取出绘制好的图片
4.保存图片到相册 
补充:把图片写入到文件的代码
1 //3.从上下文中取出绘制好的图片
2      UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
3      
4      NSData *data = UIImagePNGRepresentation(newImage);
5      
6      NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"abc.png"];
7      NSLog(@"%@", path);
8      [data writeToFile:path atomically:YES];
View Code
 
三、补充
保存成功和保存失败之后应该做些事情?
系统推荐的方法:
 1 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
 2 {
 3     if (error) {
 4         [MBProgressHUD showError:@"保存失败,请检查是否拥有相关的权限"];
 5     }else
 6     {
 7 //        [MBProgressHUD showMessage:@"保存成功!"];
 8         [MBProgressHUD showSuccess:@"保存成功!"];
 9     }
10 }
View Code

 

如果图片成功保存的话,那么就提示保存成功。
如果保存失败,那么提示失败
提示:保存失败常见有两个原因:1是内存不够,2是手机内部的权限不允许。
说明:如果当一个应用程序想要访问通讯录或相册,用户已经明确拒绝过,那么以后再要访问的话会直接拒绝。这个时候,可以提示用户去开启权限。

 

转载于:https://www.cnblogs.com/surge/p/4184098.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值