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 //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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。