iOS 问题解决记录 - UIView转换为UIImage并存入相册

910 阅读1分钟

UIView转UIImage

1、遇到需求需要将端上绘制的海报存入相册,第一步首先将对应的View转换为对应的UIImage

- (UIImage *)imageFromView:(UIView *)view {

    CGFloat viewWidth = CGRectGetWidth(view.frame);

    CGFloat viewHeight = CGRectGetHeight(view.frame);

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(viewWidth, viewHeight), **NO**, [UIScreen mainScreen].scale);

    //renderInContext 呈现接受者及其子范围到指定的上下文

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    //返回一个基于当前图形上下文的图片

    UIImage *extractImage = UIGraphicsGetImageFromCurrentImageContext();

    //移除栈顶的基于当前位图的图形上下文

    UIGraphicsEndImageContext();

    //以png格式返回指定图片的数据

    NSData *imageData = UIImagePNGRepresentation(extractImage);

    UIImage *imge = [UIImage imageWithData:imageData];

    return imge;

}

2、其次将UIImage存入相册

// 校验权限 
- (void)checkPhotoAuth {
   /**
     * PHAuthorizationStatus
     * PHAuthorizationStatusNotDetermined = 0, 用户还未决定
     * PHAuthorizationStatusRestricted,        系统限制,不允许访问相册 比如家长模式
     * PHAuthorizationStatusDenied,            用户不允许访问
     * PHAuthorizationStatusAuthorized         用户可以访问
     * 如果之前已经选择过,会直接执行 block,并且把以前的状态传给你
     * 如果之前没有选择过,会弹框,在用户选择后调用 block 并且把用户的选择告诉你
     * 注意:该方法的 block 在子线程中运行 因此,弹框什么的需要回到主线程执行
     */
    
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {        if (status == PHAuthorizationStatusAuthorized) {            [self saveImageInAlbum:[self imageFromView:self.view]];
        } else if (oldStatus != PHAuthorizationStatusNotDetermined && status == PHAuthorizationStatusDenied) {
            // 这里给用户提示开启相册权限
        }
    }];
}

- (void)saveImageInAlbum:(UIImage *)image {
    if (image) {
        @weakify(self);
        dispatch_async(dispatch_get_main_queue(), ^{
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            } completionHandler:^(**BOOL** success, NSError * _Nullable error) {
                @strongify(self);
                // 这里可以给用户一个提示
                NSString *toast = success ? @"保存到相册成功" : @"保存到相册失败";
                if (success) {
                    // 做下一步
                }
            }];
        });
    }
}