Android中的SP、DP等的关系和概念

来源:互联网 发布:南京魔苹网络能去吗 编辑:程序博客网 时间:2024/05/23 18:54

前段时间去面试自己的第一份工作,没想到面试官问了自己一个很简单的问题,但是自己并没有很好的答上来。所以在这里,自己也找了一下资料,了解了一下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
英寸 - 根据屏幕的物理尺寸。

原创粉丝点击