Android: 如何将 'dp' 转换为 'px'?

14

我正在阅读这篇文章:http://developer.android.com/guide/practices/screens_support.html

它说Android用于将dp单位转换为px单位的公式如下:

    px = dp * (dpi / 160)

该文章还举了一个dpi为240的例子,这使得px = 1.5(我在计算单个dp像素)。

但是,这里的1.5具体代表什么意思?当px单位实际上是物理设备像素时,Android会绘制1个还是2个像素?

4个回答

16

这取决于上下文。

如果在涉及大小的上下文中使用dp值,例如android:layout_width属性,则将使用Resources.getDimensionPixelSize()所描述的逻辑。也就是说,px值将四舍五入为最接近的整数值,特殊情况是如果px> 0,则实际值将至少为1。

如果在暗示偏移量的上下文中使用dp值,例如Inset Drawable的android:insetLeft属性,则将使用Resources.getDimensionPixelOffset()所描述的逻辑。也就是说,px值将简单地截断为整数值。

有时会使用未修改的浮点值,例如Shape Drawable中<stroke/>标签的android:dashWidth属性,但这相当罕见。通常使用大小或偏移逻辑之一,即使可以使用浮点值。


哦,这正是我在寻找的!不知道为什么文档没有显示这个...非常感谢Martin! - Tiago_Brasil

2
如果我所读的是正确的,1.5像素意味着单个'1'像素是指定颜色,而其周围的0.5像素将与'1'像素和相邻像素混合。例如: | A | AB | B |
A为1.5px,B为1.5px,因此中间的像素是两者的混合物。
因此,使用这种方法,两个相邻的像素将混合在一起,例如1px显示: | X | Y |
现在使用1.5px显示: | XY | YX | 它变成了两者的混合物!但是设置为X的像素将比设置为Y的像素更多地显示X。

这很有趣,但我认为这不是文章所说的。它根本没有提到颜色。我猜他们只是忘了说那个1.5到底是什么意思。我很不想说,但这就是我喜欢苹果的地方。他们的文档更加准确! - Tiago_Brasil
哦,我没有在Android文档中读到这个。这是许多现代操作系统和其他应用程序的常见功能。例如,在Web上,字体可以是1.5px,并且经常出现。浏览器计算了类似于我描述的东西。 - Micky

1

px是一像素。无缩放独立像素(sp)和密度无关像素(dip),您应该使用sp来设置字体大小,使用dip来设置其他所有内容。

dip == dp

请参考http://developer.android.com/guide/topics/resources/more-resources.html#Dimension

px
Pixels - corresponds to actual pixels on the screen.

in
Inches - based on the physical size of the screen.

mm
Millimeters - based on the physical size of the screen.

pt
Points - 1/72 of an inch based on the physical size of the screen.

dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".

sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.

0

我认为这将是最佳解决方案,因为这是标准的方法:

int valueInPx = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_PX, valueInDp, getResources().getDisplayMetrics());


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接