以下方法都在同一.m文件中
- (IBAction)buttonAction:(UIButton *)sender
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 1.捕捉
UIImage *newImage = [self captureWithView:self.view];
// 2.写文件
NSData *data = UIImagePNGRepresentation(newImage);
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"myTest.png"];
[data writeToFile:path atomically:YES];
// 3.写入到本地相册中
UIImageWriteToSavedPhotosAlbum(newImage, self, nil, nil);
});
}
/**
* 截图
*
* @param view 当前的view
*
* @return UIImage
*/
- (UIImage *)captureWithView:(UIView *)view
{
// 1.开启上下文
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
// 2.将控制器view的layer渲染到上下文
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// 3.取出图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 4.结束上下文
UIGraphicsEndImageContext();
return newImage;
}