获取设备屏幕对角线大小(英寸)

时间:2017-03-03 13:23:46

标签: xamarin xamarin.android xamarin.forms

我有Xamarin PCL项目,我有这个代码来计算设备屏幕对角线大小(英寸)(适用于Android):

public class DeviceInfoService_Droid : IDeviceInfoService
{
    public DeviceInfoModel GetDeviceInfo()
    {
        DisplayMetrics dm = new DisplayMetrics();
        IWindowManager windowManager = 
          Android.App.Application.Context.GetSystemService(
            Android.Content.Context.WindowService).JavaCast<IWindowManager>();
        windowManager.DefaultDisplay.GetMetrics(dm);
        int w = dm.WidthPixels;
        int h = dm.HeightPixels;
        double wi = (double)width / (double)dm.Xdpi;
        double hi = (double)height / (double)dm.Ydpi;
        double x = Math.Pow(wi, 2);
        double y = Math.Pow(hi, 2);
        double screenInches = Math.Sqrt(x + y);

        ...
    }
}

但对于我的5“手机,它给出了结果screenInches = 2.4173。我做错了什么?另外一个获得屏幕尺寸的解决方案也是受欢迎的。

2 个答案:

答案 0 :(得分:1)

看起来你的错误可能就在这里:

int w = dm.WidthPixels;
int h = dm.HeightPixels;
double wi = (double)width / (double)dm.Xdpi;
double hi = (double)height / (double)dm.Ydpi;

您使用widthheight代替WidthPixelsHeightPixels

我想你想要:

int w = dm.WidthPixels;
int h = dm.HeightPixels;
double wi = (double)w / (double)dm.Xdpi;
double hi = (double)h / (double)dm.Ydpi;

答案 1 :(得分:0)

我认为你做的转化太多了。

我宁愿使用:

public class DeviceInfoService_Droid : IDeviceInfoService
{
    public DeviceInfoModel GetDeviceInfo()
    {
        var metrics = Resources.DisplayMetrics;
        var widthInDp = (int)((metrics.WidthPixels) / Resources.DisplayMetrics.Density);
        var heightInDp = (int)((metrics.HeightPixels) / Resources.DisplayMetrics.Density);
        double x = Math.Pow(widthInDp , 2);
        double y = Math.Pow(heightInDp , 2);
        double screenInches = Math.Sqrt(x + y);
        .....
    }
}

编辑2: 实际上,这会为您提供Device Independant Pixels大小。以英寸为单位(取决于设备DPI):

public class DeviceInfoService_Droid : IDeviceInfoService
{
    public DeviceInfoModel GetDeviceInfo()
    {
        var metrics = Resources.DisplayMetrics;
        var widthInPx = metrics.WidthPixels;
        var heightInPx = metrics.HeightPixels;
        var heightInInches = heightInPx/metrics.ydpi;
        var widthInInches = widthInPx/metrics.xdpi;
        double x = Math.Pow(widthInInches, 2);
        double y = Math.Pow(heightInInches, 2);
        double screenInches = Math.Sqrt(x + y);
        .....
    }
}

希望它有所帮助!