简体   繁体   English

如何获得屏幕DPI

[英]How to get screen DPI

I'm trying to get the screen's dpi but so far it isn't working. 我试图获得屏幕的dpi,但到目前为止它还没有工作。 I tried: 我试过了:

    DisplayMetrics dm = new DisplayMetrics();
    mainContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
    SCREEN_DPI = dm.densityDpi;

But both on Samsung Galaxy Tab 10.1 and on Samsung Galaxy S I9000 the SCREEN_DPI is equal to 160. I also tried SCREEN_DPI = dm.density , but I get the value 1.0 to both cases. 但是在三星Galaxy Tab 10.1和三星Galaxy S I9000上,SCREEN_DPI等于160.我也尝试过SCREEN_DPI = dm.density ,但我得到的值都是1.0

Any help would be greatly appreciated. 任何帮助将不胜感激。

Duplicate of this question 这个问题重复一遍

Though Android doesn't use a direct pixel mapping, it uses a handful of quantized Density Independent Pixel values then scales that to the actual screen size. 虽然Android不使用直接像素映射,但它使用少量量化密度独立像素值,然后将其缩放到实际屏幕大小。 So the density property will be one of those constants (120, 160, or 240 dpi). 因此密度属性将是这些常数之一(120,160或240 dpi)。

If you need the actual density (perhaps for an OpenGL app) you can get it from the xdpi and ydpi properties for horizontal and vertical density respectively. 如果您需要实际密度(可能是OpenGL应用程序),您可以分别从xdpi和ydpi属性获取水平和垂直密度。

Try getRealMetrics() instead: 请尝试使用getRealMetrics()

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

This API was officially added in API 17, but in my limited testing it's worked correctly even on 4.0 devices, so it may have been a hidden API before that. 这个API在API 17中正式添加,但在我的有限测试中,即使在4.0设备上它也能正常工作,因此在此之前它可能是一个隐藏的API。

Official documentation here , though there seems to be more reasons that the other API doesn't do what you expect than the text there would imply. 这里的官方文档,虽然似乎有更多的原因,其他API没有达到你所期望的那样,而不是暗示的文本。

According to @CommonsWare: "Samsung is welcome to categorize them (the devices) to be in whatever density bucket they wish". 根据@CommonsWare的说法:“欢迎三星将它们(设备)归类为他们想要的任何密度桶”。 So, in this case, both devices are in the same density bucket. 因此,在这种情况下,两个设备都在相同的密度桶中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM