我发现可以使用DIPs在XML布局中设置界面元素的尺寸,如以下片段所示:
android:layout_width="10dip"
但是所有的Java接口都以整数作为参数,并且没有办法在DIPs中指定尺寸。计算这个值的正确方法是什么?
我想我必须使用DisplayMetrics
类的属性密度,但这是正确的方式吗?
我可以相信这个公式总是正确的吗?
像素* DisplayMetrics.density = dip
在Android中有没有用于转换的实用函数?
发布于 2010-04-21 22:26:08
有一个已构建的名为TypedValue.applyDimensions(int, float, DisplayMetrics)
的实用程序方法可以做到这一点。
下面是它的使用方法:
// returns the number of pixels for 123.4dip
int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
(float) 123.4, getResources().getDisplayMetrics());
你可以在上面链接的页面中找到其他类型的列表,包括COMPLEX_UNIT_SP
,COMPLEX_UNIT_PT
。如果你排除了(int)类型转换,你将得到浮点数。
我遇到了同样的问题,并通过查看代码发现了这一点。
发布于 2010-02-11 02:11:31
这就是正确的公式。尽管DisplayMetrics.density
不是静态成员,因此,根据same document you alluded to,正确的用法是:
// Maybe store this in a static field?
final float SCALE = getContext().getResources().getDisplayMetrics().density;
// Convert dips to pixels
float valueDips = 16.0f;
int valuePixels = (int)(valueDips * SCALE + 0.5f); // 0.5f for rounding
发布于 2011-04-27 05:17:31
使用display metrics density字段,您可以获得要转换为dips或从dips转换的比例因子。使用Math.round方法将浮点型转换为整型,而无需强制转换或添加0.5
// Converting dips to pixels
float dips = 20.0f;
float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = Math.round(dips * scale);
// Converting pixels to dips
int pixels = 15;
float scale = getContext().getResources().getDisplayMetrics().density;
float dips = pixels / scale;
https://stackoverflow.com/questions/2238883
复制相似问题