当前位置: 代码迷 >> 综合 >> android中dp与px(像素)之间的转换
  详细解决方案

android中dp与px(像素)之间的转换

热度:90   发布时间:2024-01-17 10:52:21.0
在xml布局文件中,我们既可以设置px,也可以设置dp(或者dip)。一般情况下,我们都会选择使用dp,这样可以保证不同屏幕分辨率的机器上布局一致。但是在代码中,如何处理呢?

java代码中设置大小使用的是px为单位,若要使用dp为单位,则需要进行转换;

以下是一个应用类,方便进行px和dp之间的转换。
import android.content.Context;  public class DensityUtil {  /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */  public static int dip2px(Context context, float dpValue) {  final float scale = context.getResources().getDisplayMetrics().density;  return (int) (dpValue * scale + 0.5f);  }  /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */  public static int px2dip(Context context, float pxValue) {  final float scale = context.getResources().getDisplayMetrics().density;  return (int) (pxValue / scale + 0.5f);  }  
}


  相关解决方案