以编程方式获取 Xcode 中的设备纵横比

Getting device aspect ratio in Xcode programmatically

我正在制作一款适用于所有 Apple 平台的通用游戏。问题是宽高比很多,随着设备数量的增加,这变得很麻烦。我尝试了以下方法:

var deviceAspectRatio: CGFloat? {
#if os(iOS)
    if UIDevice.current.model.contains("iPhone") {
        return 16/9
    } else if UIDevice.current.model.contains("iPad") {
        return 4/3
    }
#elseif os(tvOS)
    return 16/9 //There might be other aspect ratios also
#elseif os(watchOS)
    return 1
#elseif os(macOS)
    //figure out aspect ratio
#else
    return nil
#endif
}

但即便如此,Xcode 还是给我一个错误:

Missing return in a function expected to return 'CGFloat?'

macOS 上的诀窍是可能有多个屏幕,所以如果是这种情况,您将不得不决定您对哪个屏幕感兴趣。但是,如果您选择一个屏幕,您可以只从 NSScreen.frame 获取框架并将宽度除以高度。

此代码将获取给定 window 开启时屏幕的纵横比:

guard let frame = someWindow.screen?.frame else { return nil }
let aspectRatio = NSWidth(frame) / NSHeight(frame)

此外,您可能应该在 iOS 上使用 UIScreen 做一些类似的事情,而不是在那里对值进行硬编码。 Apple 可能有一天会发布一款新设备,其宽高比可能超出您的应用预期。

为了使其成为所有设备的通用代码,您可以使用 DeviceKit 依赖项,然后

import DeviceKit

let device = Device.current
let deviceAspectRatio = device.screenRatio.height / device.screenRatio.width

let deviceWidth = UIScreen.main.bounds.width * UIScreen.main.scale
let deviceHeight = UIScreen.main.bounds.height * UIScreen.main.scale
let testDeviceAspectRatio = deviceHeight / deviceWidth