UIImage.size的坑

本文解析了在iOS开发过程中,使用UIImage的size属性时遇到的问题及原因。指出UIImage.size.width和UIImage.size.height反映的是逻辑大小,而非实际像素尺寸。并提供了解决方案,包括如何正确获取图像的真实宽度和高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有的时候,我们做一些图片的操作。会用到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]);

 

转载于:https://www.cnblogs.com/zhang-chi/p/5620371.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值