iOS iPhone物理屏幕尺寸(以毫米为单位)

时间:2018-11-21 14:42:34

标签: ios iphone swift

有没有办法在iOS中获取以毫米为单位的iPhone物理屏幕尺寸?

唯一可用的信息是每种iPhone型号的PPI,屏幕尺寸以像素为单位,而不是以毫米为单位。

1 个答案:

答案 0 :(得分:0)

这是Swift CGSize扩展,它允许检索关于当前设备的以毫米为单位的iPhone物理屏幕尺寸:

  

注意:它仅支持iPhone X和更早的型号。

extension CGSize {
    /**
    * Physical device screen size in millimeters
    */
    static func physicalDeviceScreenSize() -> CGSize? {
        guard let ppi = deviceModelNameToPpiMapping[UIDevice().modelName], ppi != 0 else {
            return nil
        }

        let width = (UIScreen.main.nativeBounds.width * 25.4) / ppi
        let height = (UIScreen.main.nativeBounds.height * 25.4) / ppi

        return CGSize(width: width, height: height)
    }

    static private var deviceModelNameToPpiMapping: Dictionary<String, CGFloat> {
        // PPI values derived from https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
        return [
            "iPhone10,3": 458.0, // iPhone X
            "iPhone10,6": 458.0, // iPhone X
            "iPhone11,2": 458.0, // iPhone Xs
            "iPhone11,4": 458.0, // iPhone Xs Max
            "iPhone11,6": 458.0, // iPhone Xs Max
            "iPhone11,8": 326.0, // iPhone Xr
        ]
    }
}