先看一个例子:
int size = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, context.getResources().getDisplayMetrics());
这行代码是把在当前屏幕分辨率的状态下将dip为3的值转换成单位为px值
下面是API介绍:
public static float applyDimension (int unit, float value, DisplayMetrics metrics)
Since: API Level 1
Converts an unpacked complex data value holding a dimension to its final floating point value. The two parameters unit and value are as in TYPE_DIMENSION
.
Parameters
unit | The unit to convert from. |
---|---|
value | The value to apply the unit to. |
metrics | Current display metrics to use in the conversion -- supplies display density and scaling information. |
Returns
- The complex floating point value multiplied by the appropriate metrics depending on its unit.
查看其在framework中的源码
public static float applyDimension(int unit, float value, DisplayMetrics metrics) { switch (unit) { case COMPLEX_UNIT_PX: return value; case COMPLEX_UNIT_DIP: return value * metrics.density; case COMPLEX_UNIT_SP: return value * metrics.scaledDensity; case COMPLEX_UNIT_PT: return value * metrics.xdpi * (1.0f/72); case COMPLEX_UNIT_IN: return value * metrics.xdpi; case COMPLEX_UNIT_MM: return value * metrics.xdpi * (1.0f/25.4f); } return 0; }
如果传入的unit为COMPLIEX_UNIT_PX,则返回值与传入的value值保持一致;反之会根据一定的计算方式转换成px并返回。
时间: 2024-10-17 01:48:42