一、截屏
1.拖一个按钮并监听,然后实现方法
-(IBAction)clip { //延迟1 - 2秒之后再截屏(避免截的是按钮的高亮状态) dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(2.0 * NSEC_PER_SEC)),dispatch_get_main_queue(),^{ //1.开启上下文 UIGraphicsBeginImageContextWithOptions(self.view.frame.size,NO,0.0); //2.将控制器view的layer渲染到上下文 [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; //如果再拖另一个View,那么传这个View的Layer的话截图截的就是这个传的View。即截谁传谁 //3.取出绘制好的图片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //4.结束上下文 UIGraphicsEndImageContext(); } }
二、将截屏封装起来
1.新建一个类,并提供一个类方法
+(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(); //5.返回截好的图片 return newImage; }
2.实现按钮的方法
-(IBAction)clip { dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(2.0 * NSEC_PER_SEC)),dispatch_get_main_queue(),^{ //调用封装好的类方法截图 UIImage *newImage =[ UIImage captureWithView:self.view]; //写入文件 NSData *data = UIImagePNGRepresentation(newImage) ; NSString *path = [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask,YES) lastObject] stringByAppendingPathComponent:@"new.png"]; [data writeToFile:path atomically:YES]; } }