美文网首页
iOS 屏幕截图并保存到相册

iOS 屏幕截图并保存到相册

作者: rockyMJ | 来源:发表于2016-11-18 16:22 被阅读628次

首先写一个UIImage的分类

#import "UIImage+Extension.h"

@implementation UIImage (Extension)


+ (UIImage *)rendImageWithView:(UIView *)view{
    
//      1.开始位图上下文
    UIGraphicsBeginImageContext(view.frame.size);
//      2.获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
//    3.截图
    [view.layer renderInContext:ctx];
//    4.获取图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
//    5.关闭上下文
    UIGraphicsEndImageContext() ;
    
    return newImage;
    
}
@end

在需要截图的view里调用此方法

//    1.获取一个截图图片
    UIImage *newImage = [ UIImage rendImageWithView:self.view];
//    2.写入相册
    UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(image:didFinishSavingWithError:contextInfo:), @"134");

#pragma mark 用来监听图片保存到相册的状况

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        [MBProgressHUD showError:@"保存失败"];
    }else{
        [MBProgressHUD showSuccess:@"保存成功"];
    
    }
    
    NSLog(@"%@",contextInfo);
    
}

相关文章

网友评论

      本文标题:iOS 屏幕截图并保存到相册

      本文链接:https://www.haomeiwen.com/subject/xyqspttx.html