【问题标题】:Getting device aspect ratio in Xcode programmatically以编程方式在 Xcode 中获取设备纵横比
【发布时间】:2017-08-06 20:23:02
【问题描述】:

我正在制作一款适用于所有 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 还是给我一个错误:

预期返回“CGFloat”的函数中缺少返回值?

【问题讨论】:

    标签: ios xcode macos tvos watchos


    【解决方案1】:

    macOS 上的技巧是屏幕可能不止一个,所以如果是这种情况,您必须决定您对哪一个感兴趣。但是,如果您选择一个屏幕,您可以从 NSScreen.frame 中获取框架并将宽度除以高度。

    此代码将获取给定窗口所在屏幕的纵横比:

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

    此外,您可能应该在 iOS 上使用 UIScreen 执行类似的操作,而不是在那里对值进行硬编码。有朝一日,Apple 可能会发布一款您的应用无法预料到的具有其他纵横比的新设备。

    【讨论】:

    • 这就是我要说的。有没有一种通用的方法来做到这一点,而不是为每种类型的操作系统编码?喜欢Device.screen.aspectRatio? (这是伪代码)
    • 我认为没有这种方法。
    • 这个问题还没有收到完整的答案。
    【解决方案2】:

    为了使其成为所有设备的通用代码,您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 2020-02-19
      • 2017-02-15
      • 1970-01-01
      相关资源
      最近更新 更多