在android中,我們常常在xml佈局中,使用dip來進行控件大小設置,這樣可以適應不同手機屏幕,但是如果在代碼中,系統提供的方法可能只能設置px了,這樣就需要進行dip和px之間的轉換,轉換方法如下:
/** 將dip轉換成計機能能識別的像素 */
public static int dip2px(Context context, float dipValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * 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);
}
//如有不對之處,歡迎批評指正