devicekit / DeviceKit

DeviceKit is a value-type replacement of UIDevice.
MIT License
4.4k stars 425 forks source link

How to get physical Size or scale factor #328

Open alamyudi opened 1 year ago

alamyudi commented 1 year ago

Hi, very amazing library!

As far as I tried the screenRatio returns the device/simulator logical size. I am wondering is there a way to get the physical size or scale factor of the device/simulator?

Zandor300 commented 1 year ago

@alamyudi Currently, there is no way in DeviceKit to get the physical size of the device/screen. This could be a really nice addition to the library. Will look into it when I have time.

mttlmnt commented 1 year ago

Unless I'm misunderstanding, the physical screen size can be derived using the ppi feature of DeviceKit like so:

UIScreen.main.nativeBounds.width / Device.current.ppi

Or more generally:

    static var screenSize: (width: Measurement<UnitLength>, height: Measurement<UnitLength>) {
        let ppi = Device.current.ppi!
        var width = UIScreen.main.nativeBounds.width / Double(ppi)
        var height = UIScreen.main.nativeBounds.height / Double(ppi)

        if UIApplication.shared.interfaceOrientation?.isLandscape == true {
            // Swap the values, as `nativeBounds` does not change with the screen rotation
            swap(&width, &height)
        }

        return (
            width: Measurement(value: width, unit: .inches),
            height: Measurement(value: height, unit: .inches)
        )
    }