Android官方的dip to pix,dip2pix,dp2px实现
网上流传的一个常用的把dip值转换为pix像素值的方法通常是这样的:
https://blog.csdn.net/zhangphil/article/details/80613879
- public static int dip2px(Context context, float dpValue) {
- float scale = context.getResources().getDisplayMetrics().density;
- return (int) (dpValue * scale + 0.5f);
- }
大多数Android开发者也是这么转换dip和pix值的。一个偶然机会,在翻看Android TabLayout原生实现的源代码时候,发现Android官方在TabLayout里面是这样实现dip到pix值的转换的:
- int dpToPx(int dps) {
- return Math.round(getResources().getDisplayMetrics().density * dps);
- }