關於尺寸大小,主要有幾個單位需要區分開來:dp,sp,pt,px,mm,in
px:pixel,像素大小單位。在android UI中這個單位和實際的物理屏幕分辨率一樣,主要用來顯示清晰度效果。
dp:Density-independent Pixels(設備獨立像素),縮寫是dp即dip,他是一個抽象的單位,由於物理的屏幕有大有小,但dp在不同的物理屏幕上顯示的大小都是一樣的,也就是,dp和屏幕大小無關,它隻是一個抽象單位。在Android中可以用dip或dp表示,例如android:layout_width="88dp"。
在講dip之前,我們應該先瞭解dpi的概念。DPI:Dots per Inch,即每英寸包含的點,一英寸約等於2.54cm,所以dpi的概念很容易在腦海中形成瞭。DPI是用來描述圖像打印密度的單位,DPI越高,說明打印出來的圖像越細膩清晰。在72dpi的計算機中dpi就是每英寸包含的像素數。dip是針對160dpi屏幕所定義的像素單位,即在160dpi的屏幕上,1px = 1dip. dp轉化成px的計算公式是:px=dp*(density/160)。例如,對於同樣比例的4英寸屏幕,一個是160dpi,一個是320dpi,那麼20px在第一個屏幕中的寬度將是第二個中的兩倍,這樣就造成瞭比例失調,但如果是20dp,那麼在第一塊屏幕中將占20px,在第二塊中占40px,所占屏幕寬度的比例是一樣的。因此,dp消除瞭不同類型屏幕對佈局的影響。
那這個dp到底有多大?官網文檔解釋說,這個dp單位是相對於一個160dpi即160分辨率的屏幕來說的(這裡的分辨率的意思就是每英寸上點數),因此,我們說不管物理屏幕密度是多少,1英寸就等於160dp。如果分辨率是160dpi,即1英寸,根據上面的公式可知:
px=dp*(160dpi/160dpi)
px=dp*(160dp/160dp)
px=dp*1
即:1dp=1px
意思就是說:在160分辨率的屏幕上,一個dp就等於1個像素。
然後我們來看一個例子:
假如有一個手機A,他的分辨率是320*480px,然後B手機的分辨率是640*480px,A和B的尺寸是一樣的,那我們知道B手機看起來更加清晰一些。假如我們在A和B中同時畫一個按鈕,我們定義按鈕的寬度是100px,那麼根據上面的計算公式,dp和分辨率成反比,那按鈕在A手機中的dp要大,也就說我們在手機A的UI界面中看到的按鈕要比B手機中的按鈕大;如果我們定義按鈕的寬度都是100dp,那麼px和分辨率幾乎成正比,分辨率越大,那px計算得到的值就越大,就表明看起來更加清晰,而不是看起來更大。所以我們說,dp與屏幕的物理尺寸無關,而px是用來標明是否看的更加清晰。
sp:Scale-independent Pixels,比例無關的像素。這個很像dp,但是主要用來描述字體大小的,因此,sp一般是用來設定字體大小。
pt:point,中文含義是點,表示物理屏幕1尺寸的1/72。
mm和in分別表示毫米和英寸,均表示屏幕的物理大小。
總結(個人理解):dp就是試圖真正顯示的大小,而px是清晰度。因此在android的視圖設計中,要使用dp而不適用px。dp用法很廣泛,sp主要用於字體,其他的很少用。
關於這幾個尺寸官網原文是:
Dimension
A dimension value defined in XML. A dimension is specified with a number followed by a unit of measure. For example: 10px, 2in, 5sp. The following units of measure are supported by Android:
dp
Density-independent Pixels – an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, so 160dp is always one inch regardless of the screen density. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. You should use these units when specifying view dimensions in your layout, so the UI properly scales to render at the same actual size on different screens. (The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".)
sp
Scale-independent Pixels – this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference.
pt
Points – 1/72 of an inch based on the physical size of the screen.
px
Pixels – corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.
mm
Millimeters – based on the physical size of the screen.
in
Inches – based on the physical size of the screen.
作者:飛揚雲