Android小知識——手機屏幕的適配

import android.content.Context;publicclassDensityUtil{

/**     * 根據手機的分辨率從 dp 的單位 轉成爲 px(像素)     */

publicstaticint dip2px(Context context,float dpValue){

finalfloat scale = context.getResources().getDisplayMetrics().density;

return(int)(dpValue * scale +0.5f);}

/**     * 根據手機的分辨率從 px(像素) 的單位 轉成爲 dp     */

publicstaticint px2dip(Context context,float pxValue){

finalfloat scale = context.getResources().getDisplayMetrics().density;

return(int)(pxValue / scale +0.5f);}}

重點,對density的理解

float scale = getResources().getDisplayMetrics().density;

//這個得到的不應該叫做密度,應該是密度的一個比例。不是真實的屏幕密度,而是相對於某個值的屏幕密度。//也可以說是相對密度/** * The logical density of the display. This is a scaling factor for the * Density Independent Pixel unit, where one DIP is one pixel on an * approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), * providing the baseline of the system's display. Thus on a 160dpi * screen this density value will be 1; on a 120 dpi screen it would be * .75; etc. * * This value does not exactly follow the real screen size (as given by * xdpi and ydpi, but rather is used to scale the size of the overall UI * in steps based on gross changes in the display dpi. For example, a * 240x320 screen will have a density of 1 even if its width is * 1.8", 1.3", etc. However, if the screen resolution is increased to * 320x480 but the screen size remained 1.5"x2" then the density would * be increased (probably to 1.5). */

/** * 顯示器的邏輯密度,這是【獨立的像素密度單位(首先明白dip是個單位)】的一個縮放因子, * 在屏幕密度大約爲160dpi的屏幕上,一個dip等於一個px,這個提供了系統顯示器的一個基線(這句我實在翻譯不了)。 * 例如:屏幕爲240*320的手機屏幕,其尺寸爲 1.5"*2"  也就是1.5英寸乘2英寸的屏幕 * 它的dpi(屏幕像素密度,也就是每英寸的像素數,dpi是dot per inch的縮寫)大約就爲160dpi, * 所以在這個手機上dp和px的長度(可以說是長度,最起碼從你的視覺感官上來說是這樣的)是相等的。 * 因此在一個屏幕密度爲160dpi的手機屏幕上density的值爲1,而在120dpi的手機上爲0.75等等 * (這裏有一句話沒翻譯,實在讀不通順,不過通過下面的舉例應該能看懂) * 例如:一個240*320的屏幕儘管他的屏幕尺寸爲1.8"*1.3",(我算了下這個的dpi大約爲180dpi多點) * 但是它的density還是1(也就是說取了近似值) * 然而,如果屏幕分辨率增加到320*480 但是屏幕尺寸仍然保持1.5"*2" 的時候(和最開始的例子比較) * 這個手機的density將會增加(可能會增加到1.5) */

計算公式

DisplayMetrics metric =newDisplayMetrics();      

getWindowManager().getDefaultDisplay().getMetrics(metric);

int width = metric.widthPixels;// 寬度(PX)

int height = metric.heightPixels;// 高度(PX)

float density = metric.density;// 密度(0.75 / 1.0 / 1.5)

int densityDpi = metric.densityDpi;// 密度DPI(120 / 160 / 240)

需要注意的是,在一個低密度的小屏手機上,僅靠上面的代碼是不能獲取正確的尺寸的。

   比如說,一部240×320像素的低密度手機,如果運行上述代碼,獲取到的屏幕尺寸是320×427。

   因此,研究之後發現,若沒有設定多分辨率支持的話,

Android系統會將240×320的低密度(120)尺寸轉換爲中等密度(160)對應的尺寸,

   這樣的話就大大影響了程序的編碼。

   所以,需要在工程的AndroidManifest.xml文件中,加入supports-screens節點,如下:

android:smallScreens=”true”
android:normalScreens=”true”
android:largeScreens=”true”
android:resizeable=”true”
android:anyDensity=”true” />

這樣當前的Android程序就支持了多種分辨率,那麼就可以得到正確的物理尺寸了。

density = dpi/160 

px = dip * density

發佈了27 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章