一、dp、px转化
1、代码
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
2、理解
① density
- px (pixels)像素 – 是像素,就是屏幕上实际的像素点单位。
- dip或dp (device independent pixels)设备独立像素, 与设备屏幕有关。
- dpi(dot per inch):屏幕像素密度,每英寸多少像素
换算公式:px = dip * (dpi / 160)
- DisplayMetrics中的density = dpi / 160
- DisplayMetrics中的densityDpi就是dpi
/**
* The logical density of the display. This is a scaling factor for the
* Density Independent Pixel unit, where one DIP is one pixel on an
* approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen),
* providing the baseline of the system's display. Thus on a 160dpi screen
* this density value will be 1; on a 120 dpi screen it would be .75; etc.
*
* <p>This value does not exactly follow the real screen size (as given by
* {@link #xdpi} and {@link #ydpi}, but rather is used to scale the size of
* the overall UI in steps based on gross changes in the display dpi. For
* example, a 240x320 screen will have a density of 1 even if its width is
* 1.8", 1.3", etc. However, if the screen resolution is increased to
* 320x480 but the screen size remained 1.5"x2" then the density would be
* increased (probably to 1.5).
*
* @see #DENSITY_DEFAULT
*/
② 为什么要加0.5f?
- 这里涉及到一个类型转换精准度问题
- float 类型的 4.1 和4.9 强转成int类型后,会失去精准度变成 int类型的4, 而如果咱们想四舍五入的话,把他们都加上0.5f,这样转换出来的结果就是:
- 4.4 + 0.5 = 4.9 转为int 还是4,而4.5 + 0.5 = 5.0 转换成int后就是5,正好是四舍五入,这样就保证了咱们算出来的值相对精准