Android dp到厘米的转换

为了绘制地图上的比例尺,需要自己去绘制和计算比例尺的长度和对应的值 首先计算dp到英寸的关系 DisplayMetrics metrics = getRe


为了绘制地图上的比例尺,需要自己去绘制和计算比例尺的长度和对应的值


首先计算dp到英寸的关系

DisplayMetrics metrics = getResources().getDisplayMetrics();


        float result = metrics.density /  metrics.xdpi;

1dp约为result英寸


    其中metrics.density代表一个dp对应的像素值,

            metrics.xdpi代表一英寸对应的像素值,即The exact physical pixels per inch of the screen in the X dimension


因此,1dp约为result * 2.54f厘米


TypedValue.java文件


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;}