UIImage.size的坑

有的时候,我们做一些图片的操作。会用到UIImage.size.width,和UIImage.size.height作为宽高进行计算。

然而会出现一些意想不到的情况。比如下面这个例子:

clothing.png 510*628

代码:

UIImage *image = [UIImage imageNamed:@"clothing.png"];
UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:[UIScreen mainScreen].scale orientation:image.imageOrientation];
CGImageRef imageref = CGImageCreateWithImageInRect([scaledImage CGImage], CGRectMake(0, 0, scaledImage.size.width, scaledImage.size.height));
self.imageview2.image = [UIImage imageWithCGImage:imageref];

在iphone6p上运行这段代码,然后imageview2显示的内容是下面这个样子:

只显示出了左上角的一小部分。

why???

通过这个代码,你可能一下就能意识到问题在哪,就是因为这段代码:

UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:[UIScreen mainScreen].scale orientation:image.imageOrientation];

这里传递的scale是当前手机屏幕的点分辨率,iphone6p是3,所以这样得到的UIImage的size的width和height其实都是真实大小除以3。

我们查看UIImage的size属性官方文档也说了:

This value reflects the logical size of the image and takes the image’s current orientation into account. Multiply the size values by the value in the scale property to get the pixel dimensions of the image.

size是逻辑大小,真实的bitmap大小要用UIImage.size.width * UIImage.scale以及 UIImage.size.height * UIImage.scale。

或者直接使用bitmap的宽高:

CGFloat rwidth = CGImageGetWidth([scaledImage CGImage]);
CGFloat rheight = CGImageGetWidth([scaledImage CGImage]);

这里,我们直接看到UIImage的创建方式是initWithCGImage并且传递了scale为3,所以能够知道width和height是不准确的,但是实际应用中,你拿到一个UIImage,可能来自别人的模块,可能来自第三方库(比如SDWebImage)。所以如果需要使用UIImage的bitmap大小(也就是真实大小)的时候,并且不确定该UIImage是怎么创建的,一定要使用以下两种方式:

image.size.width * image.scale
image.size.height * image.scale

以及

CGFloat rwidth = CGImageGetWidth([scaledImage CGImage]);
CGFloat rheight = CGImageGetWidth([scaledImage CGImage]);

 

posted @ 2016-06-27 15:41  张驰小方块  阅读(2958)  评论(0编辑  收藏  举报