【问题标题】:Calculating android screen size?计算android屏幕大小?
【发布时间】:2012-08-29 07:49:25
【问题描述】:

是否可以以英寸为单位计算 android 屏幕对角线尺寸。

我尝试了以下两种方法,都不适合我的情况。

方法一:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int absoluteHeightInPx = displayMetrics.heightPixels;
int absoluteWidthInPx = displayMetrics.widthPixels;     
double diagonalPixels = Math.sqrt((absoluteHeightInPx * absoluteHeightInPx) + (absoluteWidthInPx * absoluteWidthInPx));
double diagonalInInches = diagonalPixels / displayMetrics.densityDpi;

方法二:

float actualHeight = absoluteHeightInPx * deviceDensity;
float actualWidth = absoluteWidthInPx * deviceDensity;
float deviceDensity = displayMetrics.density;
float physicalPixelPerInchX = displayMetrics.xdpi;
float physicalPixelPerInchY = displayMetrics.ydpi;
float heightInInches = actualHeight / physicalPixelPerInchY;
float widhtInInches = actualWidth / physicalPixelPerInchX;
double diagonalInInches = Math.sqrt((heightInInches * heightInInches) + (widhtInInches * widhtInInches));

如果我错了,你能纠正吗?

谢谢, 伊斯瓦

【问题讨论】:

标签: android android-layout mobile


【解决方案1】:

我使用下面的代码,它适用于我的 Moto Dey。

 DisplayMetrics metrics=new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    float height=metrics.heightPixels/metrics.xdpi;
    float width=metrics.widthPixels/metrics.ydpi;

    TextView tv=(TextView) findViewById(R.id.textview);
    tv.setText("The screen size is:"+FloatMath.sqrt(height*height+width*width));

实际对角线长度为3.7",代码给出3.6979072,足够精确。根据SDK中的描述,我认为我的方法应该适用于其他设备。

【讨论】:

  • 实际上你必须将 heightPixels 和 widhtPixels 与屏幕的密度相乘。如果密度 = 1,上述推导将是正确的。我认为您的设备的密度为 1。对吗?
  • SDK 文档说 xdpi 是 X 维度上每英寸的精确物理像素,而 heightPixels 是以像素为单位的绝对高度,因此将其除以 xdpi 应该得到以英寸为单位的物理长度X 维度。我就是这样考虑你的问题的。我不认为密度在这里很重要。顺便说一下,我的设备的密度是 1.5
  • 它给出的屏幕尺寸比实际屏幕大,是否有可能找到确切的物理屏幕尺寸。我在 5.5 英寸的设备上进行了测试,它给了我大约 5.8 的尺寸。
【解决方案2】:

我已经在 8 台安卓设备上测试了我的两种方法。第二个几乎是准确的。

但对于少数设备,这并没有给出正确的答案。所以我总结了第二种方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2016-12-11
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    相关资源
    最近更新 更多