dip2px 和 px2dip +0.5f是什么鬼?


public static int dip2px(Context context, float dipValue){            

final float scale = context.getResources().getDisplayMetrics().density;               
return (int)(dipValue * scale + 0.5f);  //+0.5是为了向上取整       
}     
public static int px2dip(Context context, float pxValue){                
final float scale = context.getResources().getDisplayMetrics().density;                 
return (int)(pxValue / scale + 0.5f);//+0.5是为了向上取整      

}


看官网是如何解释的:https://developer.android.com/guide/practices/screens_support.html

Converting dp units to pixel units 

The DisplayMetrics.density field specifies the scale factor you must use to convert dp units to pixels, according to the current screen density. On a medium-density screen, DisplayMetrics.density equals 1.0; on a high-density screen it equals 1.5; on an extra-high-density screen, it equals 2.0; and on a low-density screen, it equals 0.75. This figure is the factor by which you should multiply the dp units on order to get the actual pixel count for the current screen. (Then add 0.5f to round the figure up to the nearest whole number, when converting to an integer.) For more information, refer to the DisplayMetrics class.

翻译过来就是:

displaymetrics.density字段指定比例因子必须使用转换DP单位像素,根据当前屏幕的密度。在中等密度屏幕,displaymetrics.density等于1;在高密度的屏幕,它等于1.5;在超高密度的屏幕,它等于2;在低密度的屏幕,它等于0.75。这个数字的因素,你应该乘DP单位为当前屏幕获得实际的像素数。(然后添加0.5f绕图到最接近的整数,当转换成一个整数。)的更多信息,请参阅displaymetrics类。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值