繁体   English   中英

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

[英]Getting device aspect ratio in Xcode programmatically

我正在制作跨所有苹果平台的通用游戏。 问题是有很多纵横比,随着设备数量的增加,这变得很麻烦。 我尝试了以下方法:

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?”的函数中缺少返回值?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM