为不同的 iOS 设备使用不同的图像分辨率

Use different image resolutions for different iOS devices

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

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

iPhone 4s        240x240 px

iPhone 5/5s     284x284 px

iPhone 6          334x334 px

iPhone 6+        480x480 px

我查看了资产目录,但我看不出有什么方法可以为 iPhone 4s、iPhone 5/5s 和 iPhone 6 设置不同的图像(他们是 @2x)。唯一的区别是 iPhone 6+ (@3x).

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

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

有什么方法可以为每个 iOS 具有不同物理像素数量的设备使用不同的图像分辨率?

请注意,我不是询问缩放图像,而是询问使用正确的分辨率(每个的不同图像设备),因此显示时占用的内存较少。

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

@1x @2x@3x.

的 3 个比例创建 3 个不同的图像

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

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

编辑

以及关于消除您对 iPhone5 和 6 为什么使用 @2x 图像的疑虑。 好吧 iPhone5 使用与 iPhone6 相同的图像,即 @2x 图像尽管有高度,因为 iPhone5 将 @2x 缩小到它自己的极限,因此没有什么可担心的. Xcode 非常有效地解决了这个问题。

我最终只是为每个设备创建了一个不同的文件,并将它们命名为 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           dog@240.png

iPhone 5/5s        dog@284.png

iPhone 6             dog@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 ?? ""))
}