Dimension
dp(dip):
Density-independent Pixels,獨(dú)立密度像素淤堵。Android開發(fā)中常用dp來適配手機(jī)。Google規(guī)定粘勒,當(dāng)1英寸屏幕上有160個(gè)像素點(diǎn)(px)時(shí),此時(shí)1dp=1px=1dpi屎即。Google引入dp的目的是android應(yīng)用,在不同尺寸技俐、分辨率大小的手機(jī)上運(yùn)行時(shí),一個(gè)dp值可以讓Android系統(tǒng)自動(dòng)挑選Android對(duì)應(yīng)屏幕尺寸資源雕擂。也就是說:dp值可以通過某種途徑啡邑,更具設(shè)備需求井赌,得到相應(yīng)的圖片資源或者尺寸大小贵扰。
px:
Pixels,像素點(diǎn)流部。小時(shí)候家里面大屁股電視,肉眼可以看到一個(gè)一個(gè)點(diǎn)狀的東西就是像素點(diǎn)。
dpi:
dots per inch,像素密度枝冀。每一英寸(對(duì)角線長度)包含的像素點(diǎn)數(shù)除以160就是dpi舞丛。
dp果漾、px和dpi關(guān)系:
據(jù)px = dip * density / 160,則當(dāng)屏幕密度為160時(shí)绒障,px = dip
在開發(fā)中吨凑,常用的幾種轉(zhuǎn)換方式:
1.利用像素密度
Display Metricsmetrics=newDisplay Metrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int youNeedPx=(int)(metrics.density*youNeedDp+0.5f);
類似于以前的常用做法:
/**
*?根據(jù)手機(jī)的分辨率從?dp?的單位?轉(zhuǎn)成為?px(像素)
*/
public static int dip2px(Context?context,float dpValue)?{
final float scale?=?context.getResources().getDisplayMetrics().density;
return (int)?(dpValue?*?scale?+0.5f);
}
/**
*?根據(jù)手機(jī)的分辨率從?px(像素)?的單位?轉(zhuǎn)成為?dp
*/
public static int px2dip(Context?context,float pxValue)?{
final float scale?=?context.getResources().getDisplayMetrics().density;
return (int)?(pxValue?/?scale?+0.5f);
}
2.利用系統(tǒng)API
2.1TypeValue
//將50dp轉(zhuǎn)為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);