如何在代码中实现 截屏并保存至系统相册
写在前面,系统截屏并没有想象中那么难
1.保存当前界面的图片(截图)这个函数
- (UIImage *)captureCurrentView:(UIView *)view {
CGRect frame = view.frame;
UIGraphicsBeginImageContext(frame.size);
CGContextRef contextRef = UIGraphicsGetCurrentContext();
[view.layer renderInContext:contextRef];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
2.保存图片,里面方法是成功保存或者失败回调
- (void)saveImageToPhotos:(UIImage *)image {
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:),nil)
}
3.回调方法(成功或者失败),在这里可以出现个动画之类的
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error == nil) {
NSLog(@"保存成功");
} else {
NSLog(@"失败");
}
}
4.试试吧
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UIImage *image = [self captureCurrentView:self.view];
[self saveImageToPhotos:image];
}