iOS开发UI篇—Quartz2D使用(截屏)

iOS开发UI篇—Quartz2D使用(截屏)

一、简单说明

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

 

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

二、代码示例

  storyboard界面搭建:

代码:

 1 //
 2 //  YYViewController.m
 3 //  01-截屏
 4 //
 5 //  Created by apple on 14-6-12.
 6 //  Copyright (c) 2014年 itcase. All rights reserved.
 7 //
 8 
 9 #import "YYViewController.h"
10 #import "MBProgressHUD+NJ.h"
11 
12 @interface YYViewController ()
13 @property (weak, nonatomic) IBOutlet UIView *contentView;
14 - (IBAction)BtnClick:(UIButton *)sender;
15 
16 @end
17 
18 @implementation YYViewController
19 
20 - (void)viewDidLoad
21 {
22     [super viewDidLoad];
23 }
24 
25 - (IBAction)BtnClick:(UIButton *)sender {
26     
27     //延迟两秒保存
28     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
29         //获取图形上下文
30         //    UIGraphicsBeginImageContext(self.view.frame.size);
31         UIGraphicsBeginImageContext(self.contentView.frame.size);
32         //将view绘制到图形上下文中
33         
34         //    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
35         [self.contentView.layer renderInContext:UIGraphicsGetCurrentContext()];
36      
37         
38         //将截屏保存到相册
39         UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
40         
41         UIImageWriteToSavedPhotosAlbum(newImage,self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
42     });
43 }
44 
45  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
46 {
47     if (error) {
48         [MBProgressHUD showError:@"保存失败,请检查是否拥有相关的权限"];
49     }else
50     {
51 //        [MBProgressHUD showMessage:@"保存成功!"];
52         [MBProgressHUD showSuccess:@"保存成功!"];
53     }
54 }
55 
56 @end
把截取的图片保存到手机的相册中:
说明:把整个屏幕画到一张图片里
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];
三、补充
保存成功和保存失败之后应该做些事情?
系统推荐的方法:
 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 }
如果图片成功保存的话,那么就提示保存成功。
如果保存失败,那么提示失败
提示:保存失败常见有两个原因:1是内存不够,2是手机内部的权限不允许。
说明:如果当一个应用程序想要访问通讯录或相册,用户已经明确拒绝过,那么以后再要访问的话会直接拒绝。这个时候,可以提示用户去开启权限。

posted on 2014-06-12 20:14  文顶顶  阅读(9531)  评论(7编辑  收藏  举报

导航