如何在代碼中實(shí)現(xiàn) 截屏并保存至系統(tǒng)相冊(cè)
寫(xiě)在前面,系統(tǒng)截屏并沒(méi)有想象中那么難
1.保存當(dāng)前界面的圖片(截圖)這個(gè)函數(shù)
- (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.保存圖片,里面方法是成功保存或者失敗回調(diào)
- (void)saveImageToPhotos:(UIImage *)image {
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:),nil)
}
3.回調(diào)方法(成功或者失敗),在這里可以出現(xiàn)個(gè)動(dòng)畫(huà)之類(lèi)的
- (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];
}