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/