dp px转化

一、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,正好是四舍五入,这样就保证了咱们算出来的值相对精准
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值