在拍摄UIView的截图后,为什么PNG图像会变成双倍尺寸?

时间:2017-08-21 04:45:22

标签: ios objective-c uiview uiimagepngrepresentation

我可以使用以下代码从iPhone 6的UIView截取屏幕截图: -

这里我打印了2个日志。首先给我图像尺寸{375, 667},但在将其转换为PNG格式后,它会给我图像尺寸{750, 1334}

我知道它正在转换为视网膜显示器。每个点在屏幕上由2个像素表示,因此保存的图像是分辨率的两倍。

但我需要PNG格式的图片大小{375, 667}

- (UIImage *)imageWithView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSLog(@"Image Size: %@", image);  // Image Size: <UIImage: 0x1700880c0>, {375, 667}

    NSData* imageData =  UIImagePNGRepresentation(image);
    UIImage* pngImage = [UIImage imageWithData:imageData];
    UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil);

    NSLog(@"PNG Image Size: %@", pngImage);  // PNG Image Size: <UIImage: 0x174087760>, {750, 1334}

    return image;
}


大图: - enter image description here

小图片: -

enter image description here

2 个答案:

答案 0 :(得分:1)

只是为了得不到质量差,你可以用屏幕比例创建图像

但是当你加载时你可以使用这个

CGFloat screenScale = [UIScreen mainScreen].scale;
if (screenScale != img.scale) {
    img = [UIImage imageWithCGImage:img.CGImage scale:screenScale    orientation:img.imageOrientation];
}

答案 1 :(得分:0)

将比例更改为1而不是[UIScreen mainScreen].scale

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 1);