3

我有一张想在我的 iOS 应用程序中显示的图像。为了节省内存,我想显示仍与设备上的物理像素数相匹配的最低分辨率

例如,可以显示为设备高度 1/4 的正方形。所以尺寸如下

iPhone 4s         240x240 像素

iPhone 5/5s     284x284 像素

iPhone 6          334x334 像素

iPhone 6+        480x480 像素

我查看了资产目录,但我没有看到任何方法可以为 iPhone 4s、iPhone 5/5s 和 iPhone 6(它们是@2x)提供不同的图像。唯一的区别是 iPhone 6+ ( @3x)。

我也尝试添加该Retina 4 2x选项,但这只会为 iPhone 5/5s 提供不同的图标 - 仍然无法区分 4s 和 6。

在此处输入图像描述

我知道我可以根据设备以编程方式选择图像,但资产目录只会将必要的图像下载到用户设备(不确定这是否属实,不过我记得读过一些关于它的内容),从而使应用程序占用更少贮存。如果只使用一张,那么包含四张图像将是低效的。

有没有办法为每个具有不同物理像素数量的 iOS 设备使用不同的图像分辨率?

请注意,我不是要缩放图像,而是要使用正确的分辨率(每个设备都使用不同的图像),因此显示时会占用更少的 RAM。

4

2 回答 2

2

我最终只是为每个设备创建了一个不同的文件,并将它们命名为imageName@size,因此对于狗的图像128x128,文件将命名为dog@128.

这是我用来执行此操作的代码

func getPNGImageForSize(size: Float, named: String) -> UIImage?{
    //the image size will be measured in points, which is the unit that is used
    //when setting the frames of UIViews. To turn this into pixels, it must be
    //multiplied by the screen's render scale (on an iPhone 6+, 1 point is equal
    //to 3 pixels, or 9 pixels in 2 dimensions (3^2).
    let scaled: Int = Int(ceil(size * Float(UIScreen.mainScreen().scale))
    let imageName: String = "\(named)@\(scaled)"

    //ofType set to png, because this image is a PNG
    let path = NSBundle.mainBundle().pathForResource(imageName, ofType: "png")

    return UIImage(contentsOfFile: (path ?? ""))
}

要调用它,我只需使用

getPNGImageForSize(Float(self.view.frame.height / 4), named: "dog")

这将导致以下图像,具体取决于设备

iPhone 4s           狗@240.png

iPhone 5/5s         dog@284.png

iPhone 6             狗@334.png

iPhone 6+            dog@480.png

这也可以更改为使用非方形图像,命名为imageName@width-height

func getPNGImageForSize(width: Float, height: Float, named: String) -> UIImage?{  
    let scaledWidth: Int = Int(ceil(width * Float(UIScreen.mainScreen().scale))
    let scaledHeight: Int = Int(ceil(height * Float(UIScreen.mainScreen().scale))
    let imageName: String = "\(named)@\(width)-\(height)"

    let path = NSBundle.mainBundle().pathForResource(imageName, ofType: "png")

    return UIImage(contentsOfFile: (path ?? ""))
}
于 2015-09-14T05:15:32.000 回答
1

您需要将图像设置为它在 iPhone6+ 中的样子,这将消耗@3x 图像,然后缩小到其@2x 图像大小,iPhone4S 到 iPhone6 设备将使用它,然后进一步将图像缩放到@1x iPad 设备使用的早期版本。

@1x @2x用 3和3 的比例创建 3 个不同的图像@3x

只有 3 个,旧 iPhone - 3S、4、非视网膜 iPad 都消耗 @1x 图像,而 iPad Air、iPadretina、iPhone 4S - iPhone 6 使用 @2x 和 iPhone 6+ 使用 @3x 仅供参考我之前回答过这个问题这是链接

是另一个关于 IOS 设备中图像缩放的好博客(所有这些)

编辑

以及消除您对 iPhone5 和 6 为何使用@2x 图像的疑问。好吧,iPhone5 使用与 iPhone6 相同的图像,即@2x 图像,尽管 iPhone5 将@2x 缩小到自己的极限,因此无需担心这一点。Xcode 非常有效地处理了这个问题。

于 2015-09-10T05:45:27.590 回答