安卓——像素
像素
安卓支持的像素单位有:px(像素)、in(尺寸)、mm(毫米)、pt(磅,1/72英寸)、dp、dip、sp。其中,px、dp、sp最常用。
px:是手机屏幕上可显示的最小单位,与物理设备有关;
dp:与物理设备无关,同样尺寸的屏幕,使用dp设置的尺寸一样;
sp:用于设置字体大小,会随系统字体大小自动调节字体显示的大小。
像素密度:一个dp可以显示多少个像素。
在xml文件中可以用dp、sp设置尺寸,在代码中尺寸都已px为单位。如果需要在代码中利用dp值设置尺寸,需要将dp转换为sp,转换代码如下:
/**
* dp转px
*/
public static int dip2px(Context context, float dpValue){
//像素密度
float density = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * density + 0.5f);
}
/**
* px转dp
*/
public static int px2dip(Context context, float pxValue){
//像素密度
float density = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / density + 0.5);
}