IOS开发—截屏

( 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);
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//保存至相册后的回调
- ( 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];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值