标签:
iOS开发UI篇—Quartz2D使用(截屏)
一、简单说明
在程序开发中,有时候需要截取屏幕上的某一块内容,比如捕鱼达人游戏。如图:
完成截屏功能的核心代码:- (void)renderInContext:(CGContextRef)ctx;调用某个view的layer的renderInContext:方法即可
二、代码示例
storyboard界面搭建:
代码:
// // YYViewController.m // 01-截屏 // // Created by apple on 14-6-12. // Copyright (c) 2014年 itcase. All rights reserved. // #import "YYViewController.h" #import "MBProgressHUD+NJ.h" @interface YYViewController () @property (weak, nonatomic) IBOutlet UIView *contentView; - (IBAction)BtnClick:(UIButton *)sender; @end @implementation YYViewController - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)BtnClick:(UIButton *)sender { //延迟两秒保存 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //获取图形上下文 // UIGraphicsBeginImageContext(self.view.frame.size); UIGraphicsBeginImageContext(self.contentView.frame.size); //将view绘制到图形上下文中 // [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; [self.contentView.layer renderInContext:UIGraphicsGetCurrentContext()]; //将截屏保存到相册 UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext(); UIImageWriteToSavedPhotosAlbum(newImage,self, @selector(image:didFinishSavingWithError:contextInfo:), nil); }); } - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { if (error) { [MBProgressHUD showError:@"保存失败,请检查是否拥有相关的权限"]; }else { // [MBProgressHUD showMessage:@"保存成功!"]; [MBProgressHUD showSuccess:@"保存成功!"]; } } @end
//3.从上下文中取出绘制好的图片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); NSData *data = UIImagePNGRepresentation(newImage); NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"abc.png"]; NSLog(@"%@", path); [data writeToFile:path atomically:YES];
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { if (error) { [MBProgressHUD showError:@"保存失败,请检查是否拥有相关的权限"]; }else { // [MBProgressHUD showMessage:@"保存成功!"]; [MBProgressHUD showSuccess:@"保存成功!"]; } }
标签:
原文地址:http://www.cnblogs.com/yipingios/p/5557071.html