Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DPI device to PCL in Xamarin. Forms?

I need to get DPI device in my Xamarin class PCL. I do not want to use Xamarin.Essentials. Can I do this using Native interfaces, if its possible, how can I do it?

like image 835
Sp3ctre Avatar asked Dec 06 '22 10:12

Sp3ctre


1 Answers

in your pcl create a new interface called IDisplayInfo:

public interface IDisplayInfo
{
    int GetDisplayWidth();
    int GetDisplayHeight();
    int GetDisplayDpi();
}

In your android implementation, add a new class:

[assembly: Dependency(typeof(DisplayInfo))]
namespace YourAppNamespace.Droid
{
    public class DisplayInfo : IDisplayInfo
    {
        public int GetDisplayWidth()
        {
            return (int)Android.App.Application.Context.Resources.DisplayMetrics.WidthPixels;
        }

        public int GetDisplayHeight()
        {
            return (int)Android.App.Application.Context.Resources.DisplayMetrics.HeightPixels;
        }

        public int GetDisplayDpi()
        {
            return (int)Android.App.Application.Context.Resources.DisplayMetrics.DensityDpi;
        }
    }
}

and in the iOS implementation, add the same class:

[assembly: Dependency(typeof(DisplayInfo))] 
namespace YourNamespace.iOS
{
    public class DisplayInfo : IDisplayInfo
    {
        public int GetDisplayWidth()
        {
            return (int)UIScreen.MainScreen.Bounds.Width;
        }

        public int GetDisplayHeight()
        {
            return (int)UIScreen.MainScreen.Bounds.Height;
        }

        public int GetDisplayDpi()
        {
            return (int)(int)UIScreen.MainScreen.Scale;
        }
    }
}

Now in your shared code, you can call

int dpi = DependencyService.Get<IDisplayInfo>().GetDisplayDpi();

and should be good to go. Note that i also added methods for getting screen width and height, basically because i already had them in my code and since you are probably going to need them sooner or later anyways.

like image 148
Markus Michel Avatar answered Dec 28 '22 01:12

Markus Michel