iOS 截屏方法

   

static int ScreenshotIndex=0;

    

    //判断是否是retina屏

    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){

        // 开启图像上下文

        UIGraphicsBeginImageContextWithOptions(self.view.window.bounds.size, NO, [UIScreen mainScreen].scale);

    } else {

        // 开启图像上下文

        UIGraphicsBeginImageContext(self.view.window.bounds.size);

    }

    

    // 将当前视图图层渲染到当前上下文

    [self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];

    // 从当前上下文获取图像

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 关闭图像上下文

    UIGraphicsEndImageContext();

    // 保存图片到相册

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

    

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString * documentsDirectory = [paths objectAtIndex:0];

    NSString * pictureName= [NSString stringWithFormat:@"image_%d.png",ScreenshotIndex];

    self.savedImagePath = [documentsDirectory stringByAppendingPathComponent:pictureName];

    NSLog(@"截屏路径打印: %@", self.savedImagePath);

    

    NSData * data = UIImagePNGRepresentation(image);

    //保存照片到沙盒目录

    [data writeToFile:self.savedImagePath atomically:YES];

    ScreenshotIndex++;

 

 

 

    //(1)设置要截屏的图片的大小

    UIGraphicsBeginImageContextWithOptions(self.view.frame.size,NO,0);

    //(2)对哪个视图截图固定大小的图片

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

    //(3)获取截图的图片对象

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    //(4)结束绘制图片

    UIGraphicsEndImageContext();

    //(5)保存到相册

    UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);

 

posted @ 2015-08-26 14:32  tongyuling  阅读(287)  评论(0编辑  收藏  举报