android 佈局中的單位及分辨率自解

先上一個網上copy的android

px:是屏幕的像素點app

in:英寸佈局

mm:毫米字體

pt:磅,1/72 英寸google

dp:一個基於density的抽象單位,若是一個160dpi的屏幕,1dp=1pxspa

dip:等同於dp調試

sp:同dp類似,但還會根據用戶的字體大小偏好來縮放。orm

建議使用sp做爲文本的單位,其它用dipxml

而後是我本身的理解:ip

Android的屏幕密度是以160爲基準的,

屏幕密度(densityDpi)160, 是將一英寸分爲160, 每一份是1像素. 若是屏幕密度(densityDpi)240, 是將一英寸分爲240, 每一份是1像素. 1英寸/160(機器x)  =  1英寸/240(機器y)  =  1px

打個比方, 一個三英寸的顯示屏幕的機器, 若是屏幕密度(densityDpi)160, 即密度比(density)1.0, 畫一條160dip160px的線條, 兩個都是1英寸. 可若是仍是三英寸的屏幕, 若是屏幕密度(densityDpi)變爲320, 即密度比(density)2.0,1英寸有320像素了, 此時160px顯示就是半英寸. 160dip顯示仍是1英寸, 由於 1dip = 1px * density .

 

但是你有沒有注意到, 一樣寬的屏幕, 好比3英寸, 若是density 1.0的話, 分辨率就是480dip*x480px,*x 若是仍是3英寸的, density 1.5的話 , 分辨率就是480*1.5 = 720px*x 480dip*x. (這裏的x表明屏幕的高度). 若是一樣是240dip, 在兩款機器上顯示都是一半的長度, 這樣就保證了比例. 這樣的話若是是480分辨率和720分辨率的話, 能夠採用同一個佈局文件了.


又但但是, 我見過的機器只有320*240(0.75) , 480*320(1.0) , 800*480(1.5), 854*480(1.5) , 若是是480 800 兩個版本, 同一條線480dip , 480顯示全屏, 800則顯示 480 / (800 / 1.5)  . 其中800/1.5是屏幕的總dip . 咱們平時說的分辨率都是以像素px爲單位的.  

因而可知, 就算是用dip, 也不能保證不一樣分辨率的機器的佈局比例徹底同樣.  但仍是有好處的. 由於若是是用px的話, 有些時候一些佈局直接跑到了屏幕外邊, 調試起來很麻煩

還有, google代碼裏邊所用的單位都是以px爲默認單位的

apk的資源包中,當屏幕density=240時使用hdpi標籤的資源

當屏幕density=160時,使用mdpi標籤的資源

當屏幕density=120時,使用ldpi標籤的資源。

在每英寸160點的顯示器上,1dp = 1px


下面是幾種不一樣單位的相互轉換.

public static int dip2px(Context context, float dipValue){ 
final float scale = context.getResources().getDisplayMetrics().density; 
return (int)(dipValue * scale + 0.5f); 

public static int px2dip(Context context, float pxValue){ 
final float scale = context.getResource().getDisplayMetrics().density
return (int)(pxValue / scale + 0.5f); 

public static int dip2px(Context context, float dipValue){ 
final float scale = context.getResources().getDisplayMetrics().density; 
return (int)(dipValue * scale + 0.5f); 

public static int px2dip(Context context, float pxValue){ 
final float scale = context.getResource().getDisplayMetrics().density; 
return (int)(pxValue / scale + 0.5f); 


下面說下如何獲取分辨率:

    在一個ActivityonCreate方法中,寫入以下代碼:
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  //
屏幕寬度(像素)
        int height = metric.heightPixels;  //
屏幕高度(像素)
        float density = metric.density;  //
屏幕密度(0.75 / 1.0 / 1.5
        int densityDpi = metric.densityDpi;  //
屏幕密度DPI120 / 160 / 240
這仍是挺簡單的, 但是你有沒有在800*480的機器上試過, 是否是獲得的寬度是533 ? 由於android剛開始時默認的density是1.0 , 此時你能夠再manifest.xml中加入

1.uses-sdk節點, <uses-sdk android:minSdkVersion="4" /> , 表示不sdk1.6如下的機器不能安裝你的apk了.

2.supports-screens 節點. 

   <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:resizeable="true"
            android:anyDensity="true" />

相關文章
相關標籤/搜索