且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在android中以编程方式获取屏幕密度?

更新时间:2023-10-02 13:50:22

您可以从 DisplayMetrics 结构:

DisplayMetrics metrics = getResources().getDisplayMetrics();

虽然 Android 不使用直接像素映射,但它使用少量量化的密度独立像素值,然后缩放到实际屏幕尺寸.所以 metrics.densityDpi 属性将是 DENSITY_xxx 常量之一 (120, 160, 213240320480640 dpi).

Though Android doesn't use a direct pixel mapping, it uses a handful of quantized Density Independent Pixel values then scales to the actual screen size. So the metrics.densityDpi property will be one of the DENSITY_xxx constants (120, 160, 213, 240, 320, 480 or 640 dpi).

如果您需要实际 lcd 像素密度(也许对于 OpenGL 应用程序),您可以从 metrics.xdpimetrics.ydpi 水平和垂直密度的属性.

If you need the actual lcd pixel density (perhaps for an OpenGL app) you can get it from the metrics.xdpi and metrics.ydpi properties for horizontal and vertical density respectively.

如果您的目标 API 级别早于 4.metrics.density 属性是参考密度 (160dpi) 的浮点缩放因子.现在可以计算 metrics.densityDpi 提供的相同值

If you are targeting API Levels earlier than 4. The metrics.density property is a floating point scaling factor from the reference density (160dpi). The same value now provided by metrics.densityDpi can be calculated

int densityDpi = (int)(metrics.density * 160f);