一、简单说明
在程序开发中,有时候需要截取屏幕上的某一块内容,比如捕鱼达人游戏。如图:
完成截屏功能的核心代码:- (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 }