iOS 截图的实现

1,983 阅读1分钟

原理:

Quart2D绘图 图形上下文

一.普通截图

-(UIImage *)convertViewToImage:(UIView*)v{
    CGSize s = v.bounds.size;
    // 1.开启上下文 : (参数1:区域大小 ; 参数2:是否是非透明的 ; 参数3:屏幕密度,调整清晰度)
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    // 2.获取当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 3.截屏
    [v.layer renderInContext:context];
    // 4.获取图片
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    // 5.关闭上下文
    UIGraphicsEndImageContext();
    return image;
}

二.长截图

// 长截图 类型可以是 tableView或者scrollView 等可以滚动的视图 根据需要自己改
- (UIImage *)saveLongImage:(UIScrollView *)table {
    UIImage* image = nil;
    // 1.开启上下文 : (参数1:区域大小 ; 参数2:是否是非透明的 ; 参数3:屏幕密度,调整清晰度)
    UIGraphicsBeginImageContextWithOptions(table.contentSize, YES, [UIScreen mainScreen].scale);
    // 2.由于滚动视图 实现 长截图 , 所以要修改它的宽和高
    CGPoint savedContentOffset = table.contentOffset;
    CGRect savedFrame = table.frame;
    table.contentOffset = CGPointZero;
    table.frame = CGRectMake(0, 0, table.contentSize.width, table.contentSize.height);
    // 3.获取当前上下文 , 截图
    [table.layer renderInContext: UIGraphicsGetCurrentContext()];
    // 4.获取图片
    image = UIGraphicsGetImageFromCurrentImageContext();
    // 5.恢复为原来的视图
    table.contentOffset = savedContentOffset;
    table.frame = savedFrame;
    // 6.关闭上下文
    UIGraphicsEndImageContext();
    if (image != nil) {
        //保存图片到相册
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }
    return image;
}

// 保存后回调方法
- (void)image: (UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存失败" ;
    }else{
        msg = @"已保存到相册" ;
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:(UIAlertControllerStyleAlert)];
    [self presentViewController:alert animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}