将显示内容转换为图片并保存系统相册(iOS)
前言
有时候我们需要将显示内容转换为图片并保存系统相册,首先生成图片,然后在选用合适的方法进行保存。
代码
将屏幕上显示内容转换为图片1
2
3
4
5
6
7
8
9
10- (void)saveImageToPhotoLibraryAction{
CGSize size = CGSizeMake(KSCREENW, CGRectGetMaxY(self.bottomLbl.frame) + 30);
UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * bgImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(bgImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
return bgImage;
}
是否保存到系统相册1
2
3
4
5
6
7
8
9
10- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
[SVProgressHUD showInfoWithStatus:@"保存失败"];
}else{
[SVProgressHUD showSuccessWithStatus:@"已保存到系统相册"];
}
[SVProgressHUD dismissWithDelay:3];
});
}
FQA
当执行 UIImageWriteToSavedPhotosAlbum()
方法是可能会遇到以下错误信息:Error Domain=ALAssetsLibraryErrorDomain Code=-3310 “Data unavailable”…
这时需要检查代码是否书写正确,同时要保证 info.plist 中有访问相册的权限字段描述,eg:1
2
3
4<key>NSPhotoLibraryUsageDescription</key>
<string>获取图片,用于头像或上传</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>将图片保存到相册,方便分享给他人</string>
文档信息
- 版权声明:自由转载-保持署名-非商用-非衍生 ( CC BY-NC-ND 4.0 )