Android - 关于dp和pixel之间转换的困惑

Android - Puzzles about conversion between dp and pixel

我知道这可能是一个愚蠢的问题,但我真的浏览了这么多材料和链接,但仍然不太明白。在Android开发文档的“支持多屏”部分,是这样介绍dp的:

Density-independent pixel (dp)

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

基本上我理解一个事实,即具有更高 dpi 的屏幕在单个物理英寸中会有更多的像素,这意味着 在这样的屏幕中一个 dp 将等于更多的物理像素(px).

但根据上面的换算公式(粗体),在dpi较高的屏幕(如240dpi屏幕)下,px = (240 / 160) * dp = 1.5dp。这似乎意味着在更高的 dpi 屏幕上 a px 将等于更多的 dp。这看起来和我之前的理解有冲突。

那么,谁能帮我解决这个棘手的问题。非常感谢,真的。

您看错了公式中的位置。要查看不同密度下有多少 dp 等于一个 px,让我们重新排列公式:

px = dp * (dpi/160)
dp = px / (dpi/160)

现在 1px,在 mdpi 设备中:

dp = 1 / (160/160) = 1dp

在 hdpi 设备中:

dp = 1 / (240/160) = 0.666666667dp

你可以看到在更高密度的设备中 1px 等于 lessdp