如何在Xamarin中将DPI设备获取到PCL.形式? [英] How to get DPI device to PCL in Xamarin. Forms?

查看:144
本文介绍了如何在Xamarin中将DPI设备获取到PCL.形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Xamarin类PCL中获得DPI设备.我不想使用Xamarin.Essentials.如果可以的话,我可以使用本机接口执行此操作吗?

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?

推荐答案

在您的pcl中创建一个名为IDisplayInfo的新接口:

in your pcl create a new interface called IDisplayInfo:

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

在您的android实现中,添加一个新类:

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;
        }
    }
}

,然后在iOS实现中添加相同的类:

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.

这篇关于如何在Xamarin中将DPI设备获取到PCL.形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆