dip2px 和 px2dip +0.5f是什么鬼?

来源:互联网 发布:c语言编译程序的软件 编辑:程序博客网 时间:2024/06/10 17:30


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 0
原创粉丝点击