1、分类 声明方法 (category)
#import <UIKit/UIKit.h>
@interface UIImage (Mo)
+(instancetype)captureWithView:(UIView *)view;
@end
2、实现方法
#import "UIImage+Mo.h"
@implementation UIImage (Mo)//传入VIEW就可以返回VIEW上面的所有内容的截图
+(instancetype)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;
}
@end
3、在需要的地方导入头文件 调用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//延时一秒截图
UIImage * img =[UIImage captureWithView:self.view];
});
4、保存图片输出(扩展)
//输入到应用沙盒的Document文件夹里面 文件名为”new.png“
NSData *data = UIImagePNGRepresentation(newImage);
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"new.png"];
[data writeToFile:path atomically:YES];