Android unit conversion, the network has a lot of related conversion code. However, I recommend using the official conversion method TypedValue. applyDimension.
/**
* 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.
* @ 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;
}
After seeing the official conversion method, some people will ask why the network conversion method is followed by 0.5?
The reason for adding 0.5 is to ensure that the returned value is greater than 0. We have verified the TypedValue. complexToDimensionPixelSize method.
/**
* Converts a complex data value holding a dimension to its final value
* As an integer pixel size. This is the same
* {@ Link # complexToDimension}, cannot the raw floating point value is
* Converted to an integer (pixel) value for use as a size. A size
* Conversion involves rounding the base value, and ensuring that
* Non-zero base value is at least one pixel in size.
* The given <var> data </var> must be structured as
* {@ Link # TYPE_DIMENSION }.
*
* @ Param data A complex data value holding a unit, magnitude, and
* Mantissa.
* @ Param metrics Current display metrics to use in the conversion --
* Supplies display density and scaling information.
*
* @ Return The number of pixels specified by the data and its desired
* Multiplier and units.
*/
Public static int complexToDimensionPixelSize (int data,
DisplayMetrics metrics)
{
Final float value = complexToFloat (data );
Final float f = applyDimension (
(Data> COMPLEX_UNIT_SHIFT) & COMPLEX_UNIT_MASK,
Value,
Metrics );
Final int res = (int) (f + 0.5f );
If (res! = 0) return res;
If (value = 0) return 0;
If (value> 0) return 1;
Return-1;
}