Android官方dip值到pix值转换:dip2pix,dip2px,dp2px实现

Android官方的dip to pix,dip2pix,dp2px实现

网上流传的一个常用的把dip值转换为pix像素值的方法通常是这样的:

https://blog.csdn.net/zhangphil/article/details/80613879

[java]  view plain  copy
  1. public static int dip2px(Context context, float dpValue) {  
  2.     float scale = context.getResources().getDisplayMetrics().density;  
  3.     return (int) (dpValue * scale + 0.5f);  
  4. }  

大多数Android开发者也是这么转换dip和pix值的。一个偶然机会,在翻看Android TabLayout原生实现的源代码时候,发现Android官方在TabLayout里面是这样实现dip到pix值的转换的:

[java]  view plain  copy
  1. int dpToPx(int dps) {  
  2.        return Math.round(getResources().getDisplayMetrics().density * dps);  
  3.    }  

猜你喜欢

转载自blog.csdn.net/sinat_17775997/article/details/80737382