- (void)actionShot:(UIButton *)sender{ //可以隐藏按钮,渲染完后显示回来 self.buttonShot.hidden =YES; //创建图形上下文 UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.view.frame.size.width,self.view.frame.size.height),NO, 0); //获取图形上下文并将当前屏幕渲染到图形上下文上 AppDelegate *delegate = (AppDelegate *)[UIApplicationsharedApplication].delegate; [delegate.window .layerrenderInContext:UIGraphicsGetCurrentContext()]; //从图形上下文中取出绘制好的图片 UIImage *screenImage =UIGraphicsGetImageFromCurrentImageContext(); //关闭图形上下文 UIGraphicsEndImageContext(); self.buttonShot.hidden =NO; // //截屏完毕有时候可能想获取屏幕中指定区域的图片,如下操作 // //得到截屏的cgimage CGImageRef image = screenImage.CGImage; //设置目标区域,注意这里需要考虑retina分辨率的放大倍数,以iphone6plus为例,在原尺寸的基础上*3,这里就不判断了。 CGRect rect =CGRectMake(0,0, screenImage.size.width*3, screenImage.size.height*3); //取出目标区域的图片 CGImageRef targetImage =CGImageCreateWithImageInRect(image, rect); //最终图片 UIImage *finalImage = [UIImageimageWithCGImage:targetImage]; //保存到相册 UIImageWriteToSavedPhotosAlbum(finalImage,self, @selector(image: didFinishSavingWithError:contextInfo:),nil); //保存到沙盒 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)firstObject]; NSDateFormatter *dateFormatter = [[NSDateFormatteralloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSString *currentTime = [dateFormatterstringFromDate:[NSDatedate]]; NSString *imagePath = [pathstringByAppendingPathComponent:[NSStringstringWithFormat:@"ScreenShot_%@",currentTime]]; NSData *imageDate =UIImagePNGRepresentation(finalImage); [imageDate writeToFile:imagePathatomically:YES]; CGImageRelease(targetImage); }
//保存至相册后的回调 - (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo { NSString *msg =nil ; if(error !=NULL){ msg = @"保存图片失败" ; }else{ msg = @"保存图片成功" ; } UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"保存图片结果提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show]; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/lotheve/article/details/47619755