背景:
参考TypedValue.applyDimension(int unit, float value,DisplayMetrics metrics)
网上有些自己写的util,在SP、DIP转PX时 + 0.5f ,可能想四舍五入。我懒得写,直接用Android自带的TypedValue.applyDimension()
将 sp、dp 等转为 px 。
/**
* Converts an unpacked complex data value holding a dimension to its final floating
* point value. The two parameters <var>unit</var> and <var>value</var>
* are as in {@link #TYPE_DIMENSION}.
*
* @param unit The unit to convert from.
* @param value The value to apply the unit to.
* @param metrics Current display metrics to use in the conversion --
* supplies display density and scaling information.
*
* @return The complex floating point value multiplied by the appropriate
* metrics depending on its unit.
*/
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;
}
使用
背景:我要自定义一个View,有个text_size属性,默认为 16sp,否则设为布局文件中的text_size值。
于是我就可以像下面这样定义
mTextSize = (int) ta.getDimension(R.styleable.IndexBar_text_size,
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics()));
R.styleable.IndexBar_text_size
:IndexBar是自定义的View,text_size是IndexBar中自定义的属性;
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics())
:默认16sp。若只传16,getDimension会当作 Px 直接返回。(@Px提示)