android屏幕 单位转换
在android内部会使用TypedValue.applyDimension函数将所有单位换算成px。
1 public static float applyDimension(int unit, float value, 2 DisplayMetrics metrics) 3 { 4 switch (unit) { 5 case COMPLEX_UNIT_PX: 6 return value; 7 case COMPLEX_UNIT_DIP: 8 return value * metrics.density; 9 case COMPLEX_UNIT_SP: 10 return value * metrics.scaledDensity; 11 case COMPLEX_UNIT_PT: 12 return value * metrics.xdpi * (1.0f/72); 13 case COMPLEX_UNIT_IN: 14 return value * metrics.xdpi; 15 case COMPLEX_UNIT_MM: 16 return value * metrics.xdpi * (1.0f/25.4f); 17 } 18 return 0; 19 }
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.
这里也给一个[男人应似海http://www.cnblogs.com/wader2011/archive/2011/11/28/2266684.html]写的转换工具类。
1 /** 2 * Android大小单位转换工具类 3 * 4 * @author wader 5 * 6 */ 7 public class DisplayUtil { 8 /** 9 * 将px值转换为dip或dp值,保证尺寸大小不变 10 * 11 * @param pxValue 12 * @param scale(DisplayMetrics类中属性density) 13 * @return 14 */ 15 public static int px2dip(float pxValue, float scale) { 16 return (int) (pxValue / scale + 0.5f); 17 } 18 19 /** 20 * 将dip或dp值转换为px值,保证尺寸大小不变 21 * 22 * @param dipValue 23 * @param scale(DisplayMetrics类中属性density) 24 * @return 25 */ 26 public static int dip2px(float dipValue, float scale) { 27 return (int) (dipValue * scale + 0.5f); 28 } 29 30 /** 31 * 将px值转换为sp值,保证文字大小不变 32 * 33 * @param pxValue 34 * @param fontScale(DisplayMetrics类中属性scaledDensity) 35 * @return 36 */ 37 public static int px2sp(float pxValue, float fontScale) { 38 return (int) (pxValue / fontScale + 0.5f); 39 } 40 41 /** 42 * 将sp值转换为px值,保证文字大小不变 43 * 44 * @param spValue 45 * @param fontScale(DisplayMetrics类中属性scaledDensity) 46 * @return 47 */ 48 public static int sp2px(float spValue, float fontScale) { 49 return (int) (spValue * fontScale + 0.5f); 50 } 51 }
原创文章欢迎转载,转载请注明出处:http://www.cnblogs.com/zhouchanwen