如何在代码中实现 截屏并保存至系统相册
写在前面,系统截屏并没有想象中那么难
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];
}
网友评论
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let img : UIImage = UIGraphicsGetImageFromCurrentImageContext()! // 截取到的图像
UIGraphicsEndImageContext() // 结束截取
void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
size——同UIGraphicsBeginImageContext
opaque—透明开关,如果图形完全不用透明,设置为YES以优化位图的存储。
scale—–缩放因子
这里需要判断一下UIGraphicsBeginImageContextWithOptions是否为NULL,因为它是iOS 4.0才加入的 设置为0就不会模糊了
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
这个方法的ERROR 是怎么来的? contextInfo 有什么用啊