Android中dip(dp)与px之间单位转换

Androiddip(dp)px之间单位转换

 

dp这个单位可能对web开发的人比较陌生,因为一般都是使用px(像素)

但是,现在在开始android应用和游戏后,基本上都转换成用dp作用为单位了,因为可以支持多种分辨率的手机.

以下是这两个单位的概念:

px (pixels)像素 –一个像素通常被视为图像的最小的完整采样,这个用的比较多,特别是web开发,页面基本都是使用像素作为单位的.

dipdp (device independent pixels)设备独立像素 这个和设备硬件有关,一般我们为了支持手机上多种分辨率,WVGAHVGAQVGA,都会使用dip作为长度的单位

Android开发我们一般都可以不需要使用px,但是某一些控件的属性没有直接支持dip,像下面的代码

 

android.view.ViewGroup.LayoutParams.height

android.view.ViewGroup.LayoutParams.width上面这两个属性的单位为像素,但是为了兼容多种分辨率的手机,我们需要最好使用dip,时候我们可以调用以下的代码进行转换.

int heightPx= DisplayUtil.dip2px(this, 33);

mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = heightPx;

以上代码可以在我另一篇文章看得到.该功能是设置Tab的高度,单位是像素.以上的单位转换是为了支持多分辨率手机的.

该文章的地址 : [AndroidTabHost的使用]

/**

 * 根据手机的分辨率从 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);

}

posted on 2012-08-23 14:32  1.曲待续  阅读(182)  评论(0编辑  收藏  举报

导航