Android中的SP、DP等的關係和概念

前段時間去面試自己的第一份工作,沒想到面試官問了自己一個很簡單的問題,但是自己並沒有很好的答上來。所以在這裏,自己也找了一下資料,瞭解了一下Android中的px、sp、dp等的相關內容。

  Android的developer網站上的介紹:

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, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi. Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.
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, assuming a 72dpi density 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.

翻譯過來是這樣的:

在XML中定義的維度值。一個維度用一個數字後跟一個度量單位來指定。例如:10px,2in,5sp。 Android支持以下測量單位:

DP
密度無關像素 - 基於屏幕物理密度的抽象單位。這些單位是相對於160 dpi(每英寸點數)的屏幕,其中1dp大約等於1px。當在較高密度的屏幕上運行時,用於繪製1dp的像素數量按照適合屏幕dpi的因子進行放大。同樣,當在較低密度的屏幕上,縮放用於1dp的像素數量。 dp對像素的比例將隨着屏幕密度而變化,但不一定是正比例的。使用dp單位(而不是px單位)是一種簡單的解決方案,使您的佈局中的視圖尺寸適當調整不同的屏幕密度。換句話說,它爲不同設備的UI元素的真實世界大小提供一致性。
SP
與尺寸無關的像素 - 這就像dp單位,但它也被用戶的字體大小偏好縮放。建議您在指定字體大小時使用本機,因此將根據屏幕密度和用戶偏好進行調整。
PT
點 - 基於屏幕物理尺寸的1/72英寸,假設屏幕爲72dpi。
PX
像素 - 對應於屏幕上的實際像素。不推薦使用此計量單位,因爲實際的顯示可能會因設備而異;每個設備可以具有每英寸不同數量的像素,並且可以具有更多或更少的屏幕上可用的總像素。
MM
毫米 - 根據屏幕的物理尺寸。
IN
英寸 - 根據屏幕的物理尺寸。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章