Android 将 Px 转换为 Dp(视频宽高比)

标签 android screen-resolution aspect-ratio

Possible Duplicate:
converting pixels to dp in android

我正在尝试将像素转换为 dp。公式是什么?

让我们将 640 和 480 转换为 dp。文档是这样说的

The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160)

但我认为这不是我需要的(而且我不知道如何使用它)。我想我只需要forumla。我已经准备好了代码:

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

    switch(metrics.densityDpi)
    {
         case DisplayMetrics.DENSITY_LOW:
         int sixForty = ?
         int fourEighty = ?
         break;

         case DisplayMetrics.DENSITY_MEDIUM:
         int sixForty = ?
         int fourEighty = ?
         break;

         case DisplayMetrics.DENSITY_HIGH:
         int sixForty = ?
         int fourEighty = ?
         break;
    }

最佳答案

不要试图从屏幕的密度分类中推断出dp转换因子,你可以直接查询它:

getWindowManager().getDefaultDisplay().getMetrics(metrics);
float logicalDensity = metrics.density;

logicalDensity 将包含您需要乘以 dp 以获得设备屏幕的物理像素尺寸的因子。

int px = (int) Math.ceil(dp * logicalDensity);

关于Android 将 Px 转换为 Dp(视频宽高比),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6656540/

相关文章:

c# - Unity C# 四元数 : Swap y with z axis

android - 如何在 Google Play 应用说明中包含要点?

android - 多屏幕分辨率

OpenGL 拉伸(stretch)形状 - 纵横比

java - 当服务在后台工作时,AsyncTask 的 doInBackground 从未被调用

Android Navigation drawer Header 颜色变化

screen-resolution - Unity 5.2.1 的 Screen.currentResolution

android - Nodpi 图像与 Android 1.5

html - 使用 CSS 保持 div 的纵横比