【发布时间】:2012-07-05 13:37:42
【问题描述】:
我有一组按钮和不同大小的图像。我想缩放每个图像,以便它以正确的纵横比适合按钮。缩放图像后,我将按钮的图像属性设置为缩放版本。
UIImage *scaledImage = [image scaledForButton:pickerButton];
[pickerButton setImage:scaledImage forState:UIControlStateNormal];
我的 scaledForButton 方法是在 UIImage 的类扩展中定义的。它看起来像这样:
- (UIImage *)scaledForButton:(UIButton *)button
{
// Check which dimension (width or height) to pay respect to and
// calculate the scale factor
CGFloat imageRatio = self.size.width / self.size.height;
CGFloat buttonRatio = button.frame.size.width / button.frame.size.height;
CGFloat scaleFactor = (imageRatio > buttonRatio ? self.size.width/button.frame.size.width : self.size.height/button.frame.size.height);
// Create image using scale factor
UIImage *scaledimage = [UIImage imageWithCGImage:[self CGImage]
scale:scaleFactor
orientation:UIImageOrientationUp];
return scaledimage;
}
当我在 iPad2 上运行它时,它工作正常并且图像缩放正确。但是,如果我在视网膜显示器(模拟器和设备上)上运行它,图像无法正确缩放并被挤压到按钮中。
任何想法为什么这只会发生在视网膜上?这几天我一直在挠头,但无法弄清楚。他们都运行相同的 iOS,我检查了比例和比例输出,无论设备如何,它们总是相同的。非常感谢。
【问题讨论】:
-
它可能是 "CGFloat scaleFactor = (imageRatio > buttonRatio)? self.size.width/button.frame.size.width : self.size.height/button.frame.size.height; "
-
您在 iPad2 和新 iPad 中都记录了“buttonRatio”吗?
-
是的,我已经为这两种设备记录了它们,并且每次都相同。我使用 2x 图像进行视网膜显示。程序是否可能正在调整 1x 的大小,然后改用 2x?
-
你检查过CGImage的尺寸吗?视网膜情况下 CGImage 的尺寸将是非视网膜版本的两倍。 (或者不是?)但是 UI... 坐标中的 scaleFactor 总是相同的。
-
只是提供一个替代方案:我个人会使用 .contentMode 并将图像分配给按钮大小的临时图像视图。 contentMode 可能会因(imageRatio > buttonRatio)而异,但不一定会有所不同(我不太确定您想要实现什么)。然后确定图像视图的 .image 的大小并从那里开始。
标签: objective-c ios xcode uiimage cgimage