iOS使用我自己的图像后缀时图像尺寸错误

时间:2013-06-29 15:45:03

标签: ios iphone ipad retina-display

我使用适用于iPhone的bg.png,适用于iPhone视网膜和iPad的bg @ 2x,适用于iPad视网膜的bg @ 4x。 这是我写的代码:(在Helper.m中)

+ (UIImage *) imageNamed:(NSString *)name
{
    name = [name stringByReplacingOccurrencesOfString:@".png" withString:@""];
    UIImage *image;
    if (IS_IPAD) {
        if (IS_RETINA) {
            image = [UIImage imageNamed:[NSString stringWithFormat:@"%@@4x.png", name]];
            if (image) {
                return image;
            }
        }

        return [UIImage imageNamed:[NSString stringWithFormat:@"%@@2x.png", name]];
    }
    else {
        if (IS_RETINA) {
            image = [UIImage imageNamed:[NSString stringWithFormat:@"%@@2x.png", name]];
            if (image) {
                return image;
            }
        }
        return [UIImage imageNamed:name];
    }
}

文件正确,但图片大小错误。

如果系统自动选择文件(使用[UIImage imageNamed:@"bg.png"]),则在iPhone视网膜上,大小仍为320x480(1点= 4像素)。

但如果我使用[Helper imageNamed:@"bg.png"],则尺寸为640x960。 (1分= 1像素)

所以无论如何要改正尺寸?

2 个答案:

答案 0 :(得分:8)

在视网膜设备上

 [UIImage imageNamed:@"bg.png"]

首先搜索bg@2x.png。如果该图像存在,则加载它并使用scale属性 图像的自动设置为2.0。另一方面,

 [UIImage imageNamed:@"bg@2x.png"]

也会加载该图片,但会使用默认的scale = 1.0

如果 您必须使用自定义加载机制,则必须调整比例因子。 由于scaleUIImage的只读属性,因此无法直接设置。一种方法 我知道是

UIImage *tmpImage = [UIImage imageNamed:@"bg@2x.png"];
UIImage *properlyScaledImage = [UIImage imageWithCGImage:[tmpImage CGImage]
                                           scale:2.0
                                     orientation:UIImageOrientationUp];

答案 1 :(得分:5)

为什么要重新发明Apple已提供的产品? imageNamed:方法已支持使用~iphone~ipad后缀加载iPhone或iPad特定图片的功能。

要获取iPad特定的视网膜图像,只需将其命名为bg@2x~ipad.png即可。 要获取iPad特定的非视网膜图像,请将其命名为bg~ipad.png

您的代码遇到的问题是由于非标准的命名约定,图像加载的是错误的比例。

更新:根据评论中的其他信息,解决此问题的更好方法是将UIImage imageNamed:方法的使用替换为UIImage imageWithData:scale:方法的调用。这提供了更好的内存管理,以及为iPhone视网膜和iPad非视网膜之间的自定义命名约定和图像共享指定适当比例的能力。

相关问题