Dimension
dp(dip):
Density-independent Pixels,獨立密度像素。Android開發中常用dp來適配手機。Google規定,當1英寸屏幕上有160個像素點(px)時,此時1dp=1px=1dpi。Google引入dp的目的是android應用,在不同尺寸、分辨率大小的手機上運行時,一個dp值可以讓Android系統自動挑選Android對應屏幕尺寸資源。也就是說:dp值可以通過某種途徑,更具設備需求,得到相應的圖片資源或者尺寸大小。
px:
Pixels,像素點。小時候家里面大屁股電視,肉眼可以看到一個一個點狀的東西就是像素點。
dpi:
dots per inch,像素密度。每一英寸(對角線長度)包含的像素點數除以160就是dpi。
dp、px和dpi關系:
據px = dip * density / 160,則當屏幕密度為160時,px = dip
在開發中,常用的幾種轉換方式:
1.利用像素密度
Display Metricsmetrics=newDisplay Metrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int youNeedPx=(int)(metrics.density*youNeedDp+0.5f);
類似于以前的常用做法:
/**
*?根據手機的分辨率從?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);
}
2.利用系統API
2.1TypeValue
//將50dp轉為px
int defaultMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,50,getResources().getDisplayMetrics());
//源代碼如下
public static float applyDimension(int unit, float value,DisplayMetrics metrics){
switch(unit) {
case COMPLEX_UNIT_PX:
return value;
//dip像素密度
case COMPLEX_UNIT_DIP:
return value * metrics.density;
case COMPLEX_UNIT_SP:
return value * metrics.scaledDensity;
//pt:point 印刷中 磅
case COMPLEX_UNIT_PT:
return value * metrics.xdpi* (1.0f/72);
case COMPLEX_UNIT_IN:
return value * metrics.xdpi;
case COMPLEX_UNIT_MM:
returnvalue * metrics.xdpi* (1.0f/25.4f);
}
return0;
}
2.2從資源文件中獲取
《?xmlversion="1.0" encoding="utf-8"?》
《resources》
《dimen name="thumbnail_height"》120dp《/dimen》
...
...
《/resources》
//將以上《換成<
Then in your Java:
getResources().getDimensionPixelSize(R.dimen.thumbnail_height);