Skip to content

Instantly share code, notes, and snippets.

@rockswang
Created February 9, 2014 11:44
Show Gist options
  • Save rockswang/8897953 to your computer and use it in GitHub Desktop.
Save rockswang/8897953 to your computer and use it in GitHub Desktop.
android 单位之间的换算 TypedValue 我们知道 TypedValue 中有个applyDimension(int unit, float value, DisplayMetricsmetrics) 方法,通过这个方法可以将各种单位装换成像素,现在就来看看这个方法是如何实现的,也就知道了他们之间的转换关系,首先看源码:
/**
* 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;
}
以dip为例,他们的转换关系显而易见:px = dip * 密度(metrics.density)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment