对控件截屏并保存到系统相册
2019-06-11 本文已影响0人
黄定师
前言
项目中有个需求就是对某个控件截屏,并将截屏的图片保存到系统相册。这里记录下我的实现过程。
实现过程
在具体实现时,我将它们封装到一个专门的类里。下面是主要的代码。
#pragma mark - 截屏
+ (UIImage *)snapshotForView:(UIView *)view {
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshotImage;
}
#pragma mark - 保存图片到相册
// 记得导入头文件#import <Photos/Photos.h>
+ (void)saveToAlbum:(UIImage *)img completionHandler:(void(^)(BOOL))handler {
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status != PHAuthorizationStatusAuthorized) return;
// 保存相片到相机胶卷
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:img];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(success);
});
}
}];
}];
}