我正在阅读这篇文章: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个像素?
我正在阅读这篇文章: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个像素?
这取决于上下文。
如果在涉及大小的上下文中使用dp值,例如android:layout_width
属性,则将使用Resources.getDimensionPixelSize()所描述的逻辑。也就是说,px值将四舍五入为最接近的整数值,特殊情况是如果px> 0,则实际值将至少为1。
如果在暗示偏移量的上下文中使用dp值,例如Inset Drawable的android:insetLeft
属性,则将使用Resources.getDimensionPixelOffset()所描述的逻辑。也就是说,px值将简单地截断为整数值。
有时会使用未修改的浮点值,例如Shape Drawable中<stroke/>
标签的android:dashWidth
属性,但这相当罕见。通常使用大小或偏移逻辑之一,即使可以使用浮点值。
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.
我认为这将是最佳解决方案,因为这是标准的方法:
int valueInPx = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_PX, valueInDp, getResources().getDisplayMetrics());