我同意 Yun CHEN 的观点,因为我认为最安全的解决方案是为每个分辨率设置一个 Image Set,从而避免在设备上执行图像缩放。
同样正确的是,根据设备的渲染因子(2x、3x 等)(例如 4.7 英寸 iPhone 上的 2x,如 iPhone 8),您只需放置适当大小的图像在相应的插槽中。
例如,iPhone 8 的图像集只需要 2x 图像。
但是,请注意以下几点:
UIScreen.main.bounds.height 返回逻辑分辨率的高度 - 即点,与返回实际分辨率的高度 - 即像素(实际上,UIScreen.main.nativeBounds.height 始终返回设备在纵向模式下的像素高度,即使您处于横向模式也是如此)。 您应始终使用与实际分辨率(即像素)相匹配的图像,即使您检查点也是如此。
从 iOS 8 开始,无论您的设备处于纵向还是横向模式,UIScreen.main.bounds.height 都会返回不同的值。
因此,如果您想使用它来区分设备,您应该检查您的 App 可以使用的所有值,并且您应该为每个值设置一个单独的 Image Set。
例如,对于同时在纵向和横向模式下工作的应用程序:
var backgroundImageName = ""
if UIDevice().userInterfaceIdiom == .phone
{
switch UIScreen.main.bounds.height
{
case 812: // 5.8" (iPhone X) (3x) (Portrait)
backgroundImageName = "background_1125x2436"
case 736: // 5.5" (iPhone 8+, 7+, 6s+, 6+) (3x) (Portrait)
backgroundImageName = "background_1242x2208"
case 414: // 5.5" (iPhone 8+, 7+, 6s+, 6+) (3x) (Landscape)
backgroundImageName = "background_2208x1242"
case 667: // 4.7" (iPhone 8, 7, 6s, 6) (2x) (Portrait)
backgroundImageName = "background_750x1334"
case 375:
// 5.8" (iPhone X) (3x) (Landscape)
if (UIScreen.main.bounds.width == 812) {
backgroundImageName = "background_2436x1125"
}
// 4.7" (iPhone 8, 7, 6s, 6) (2x) (Landscape)
else if (UIScreen.main.bounds.width == 667) {
backgroundImageName = "background_1334x750"
}
case 568: // 4.0" (iPhone SE, 5s, 5c, 5) (2x) (Portrait)
backgroundImageName = "background_640x1136"
case 320: // 4.0" (iPhone SE, 5s, 5c, 5) (2x) (Landscape)
backgroundImageName = "background_1136x640"
default:
break
}
}
else if UIDevice().userInterfaceIdiom == .pad
{
switch UIScreen.main.bounds.height
{
case 1366: // 12.9" (iPad Pro 12.9) (2x) (Portrait)
backgroundImageName = "background_2048x2732"
case 1112: // 10.5" (iPad Pro 10.5) (2x) (Portrait)
backgroundImageName = "background_1668x2224"
case 834: // 10.5" (iPad Pro 10.5) (2x) (Landscape)
backgroundImageName = "background_2224x1668"
case 1024:
// 12.9" (iPad Pro 12.9) (2x) (Landscape)
if (UIScreen.main.bounds.width == 1366) {
backgroundImageName = "background_2732x2048"
}
// 9.7" & 7.9" (iPad Pro 9.7, iPad Air 2, iPad Air, iPad 4, iPad 3, iPad Mini 4, iPad Mini 3, iPad Mini 2) (2x) (Portrait)
else if (UIScreen.main.bounds.width == 1366) {
backgroundImageName = "background_1536x2048"
}
case 768: // 9.7" & 7.9" (iPad Pro 9.7, iPad Air 2, iPad Air, iPad 4, iPad 3, iPad Mini 4, iPad Mini 3, iPad Mini 2) (2x) (Landscape)
backgroundImageName = "background_2048x1536"
default:
break
}
}
self.backgroundImageView.image = UIImage(named: backgroundImageName)
如果需要包含其他设备(例如 Apple Watch),则依此类推。