zoukankan      html  css  js  c++  java
  • Android中dp和px之间进行转换

    在xml布局文件中,我们既可以设置px,也可以设置dp(或者dip)。一般情况下,我们都会选择使用dp,这样可以保证不同屏幕分辨率的机器上布局一致。但是在代码中,如何处理呢?很多控件的方法中都只提供了设置px的方法,例如setPadding,并没有提供设置dp的方法。这个时候,如果需要设置dp的话,就要将dp转换成px了。

    以下是一个应用类,方便进行px和dp之间的转换。

    1. import android.content.Context;  
    2.   
    3. public class DensityUtil {  
    4.   
    5.     /** 
    6.      * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
    7.      */  
    8.     public static int dip2px(Context context, float dpValue) {  
    9.         final float scale = context.getResources().getDisplayMetrics().density;  
    10.         return (int) (dpValue * scale + 0.5f);  
    11.     }  
    12.   
    13.     /** 
    14.      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
    15.      */  
    16.     public static int px2dip(Context context, float pxValue) {  
    17.         final float scale = context.getResources().getDisplayMetrics().density;  
    18.         return (int) (pxValue / scale + 0.5f);  
    19.     }  
    20. }  

    http://blog.csdn.net/arui319

     

  • 相关阅读:
    组件库设计
    kill 3000
    nextjs服务端渲染原理
    Web交互增强
    webpack4.0打包的时候一些技巧
    把网站部署到阿里云上的步骤
    typescript使用小结
    webpack 4.0尝鲜
    基于Quick-cocos2d-x的资源更新方案 二
    Android APK是否需要预解压
  • 原文地址:https://www.cnblogs.com/cmblogs/p/4828857.html
Copyright © 2011-2022 走看看