你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS開發—截屏

IOS開發—截屏

編輯: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);
}

 

//保存至相冊後的回調
- (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];
}

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved