计算Android屏幕尺寸?

4

是否有可能在英寸中计算Android屏幕对角线尺寸。

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

方法1:

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

如果我说错了,请您纠正。

谢谢, Easwar


https://dev59.com/53I95IYBdhLWcg3wsQL9 - Will Richardson
我已经看过那个链接。但是这对我来说不起作用。我在一些设备上进行了测试,但没有得到完美的答案。请帮助我。 - Easwaramoorthy K
2个回答

7

我使用下面的代码,在我的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。对吗? - Easwaramoorthy K
SDK文档指出xdpi是X轴方向上每英寸的物理像素数,heightPixels是绝对像素高度,因此将其除以xdpi即可得到X轴方向上的物理长度。这就是我考虑你的问题的方式。我认为密度在这里并不重要。顺便说一下,我的设备密度为1.5。 - Huang
1
它给出的屏幕尺寸比实际屏幕要大,有没有可能找到准确的物理屏幕尺寸。我在5.5英寸的设备上测试过,它给出的尺寸约为5.8。 - Dory

-1

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

但是对于一些设备,这并没有给出正确的答案。因此,我得出结论,采用第二种方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接