Search code examples
c#mauidpiskiasharpppi

.net MAUI How to get DPi/PPi cross platform


Get DPI/PPI

Hello,

How can one get the DPI or PPI in Maui for every platform?

I could only find DeviceDisplay.MainDisplayInfo.Density, but this gives me only the scaling of the display like 1,2 and so on...
It also provides the Height, and width in Pixels but no Display Inch Information or something i could calculate the dpi or ppi value.

Beside i could only find some Windows specific approaches, but that does not help me as i need it for Android and iOs too.

Why i need this?
Cause i like to convert my skiashap text, linex, and so on... to real cm and vice versa.

Thanks for every help!


Solution

  • Though there is no direct way to obtain the PPI of the mobile device. You may try using platform code to count the DPI value yourself.

    You may know the definition of a mobile device's PPI, which stands for Pixels Per Inch. As long as we get the screen size and screen pixels, we could obtain the PPI value.

    For example, Android has DisplayMetrics class, which can describe general information about a display. You may try the following code to count PPI

    #if ANDROID
                var dm = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.Resources?.DisplayMetrics;
                var x = Math.Pow(dm.WidthPixels / dm.Xdpi, 2);
                var y = Math.Pow(dm.HeightPixels / dm.Ydpi, 2);
                var ScreenSize = Math.Sqrt(x + y);
            
                var ScreenPixels = Math.Pow(dm.WidthPixels, 2) + Math.Pow(dm.HeightPixels, 2);
                var a = Math.Sqrt((double)ScreenPixels);
    
                var ppi = a / ScreenSize;
    
    #endif
    

    For iOS, I think there is no API to get the PPI value. You may refer to How to find PPI programmatically with precision. Since we cannot get the physical screen size of an iPhone, we cannot count PPI, or we have to hardcode each device's screen size or PPI in the program. That means we have to update when a new iOS device is released.

    Here is also a similar issue on SO, How to get points or pixels per inch of device using xamarin.iOS project?