IOS 截屏(保存到相册中)

 

 

@interface NJViewController ()
/**
 *  点击截屏按钮
 */
- (IBAction)captureView:(UIButton *)sender;
/**
 *  白色view
 */
@property (weak, nonatomic) IBOutlet UIView *customView;

@end

@implementation NJViewController
- (IBAction)captureView:(UIButton *)sender {
    
    // 延迟1 ~2 秒之后再截屏
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 1.创建一个bitmap的上下文
        UIGraphicsBeginImageContext(self.view.frame.size);
        
        
        // 2.将屏幕绘制到上下文中
//        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        
         UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        /*
        // 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];
        */
        
        // 4.保存图片到相册
        
        UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    });

}

 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
//    NSLog(@"completionImage");
    
    if (error) {
//        NSLog(@"保存失败");
        [MBProgressHUD showError:@"保存失败, 请检测应用是否拥有访问相册的权限"];
    }else
    {
//        NSLog(@"保存成功");
        [MBProgressHUD showSuccess:@"保存成功"];
    }
}

 

posted on 2017-03-22 11:05  守望星空  阅读(252)  评论(0编辑  收藏  举报

导航