Android学习笔记--尺寸单位

来源:互联网 发布:感恩节文案 知乎 编辑:程序博客网 时间:2024/06/05 20:20

一。Android中支持的尺寸单位

单位表示单位名称单位说明px像素屏幕上的真实像素表示in英尺基于屏幕的物理尺寸表示mm毫米基于屏幕的物理尺寸表示pt点英尺的1/72dp和密度无关的像素相对屏幕物理密度的抽象单位sp和精度无关的像素类似于dp二。dp与sp

在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 inchregardless 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".)

这里牵涉到一个dpi的概念,也就是一英寸屏幕里面有多少个像素点,这就是这里所谓的Density密度。dp的密度无关也就是排除各种屏幕dpi不同而导致的显示规格不同,sp是在dp的基础上还与scale无关,这里的scale应该是指的是屏幕大小,也就是平常所说的几寸几寸屏。

如果屏幕密度为160,这时dp和sp和px是一样的。1dp=1sp=1px,但如果使用px作单位,如果屏幕大小不变(假设还是3.2寸),而屏幕密度变成了320。那么原来TextView的宽度设成160px,在密度为320的3.2寸屏幕里看要比在密度为160的3.2寸屏幕上看短了一半。但如果设置成160dp或160sp的话。系统会自动将width属性值设置成320px的。也就是160 * 320 / 160。其中320 / 160可称为密度比例因子。

也就是说,如果使用dp和sp,系统会根据屏幕密度的变化自动进行转换.所以在我们的应用程序中,提倡使用sp、dp来适应各种不同的屏幕。

原创粉丝点击