关于dpi、dp与sp的基础了解

来源:互联网 发布:cnki网络数据库 编辑:程序博客网 时间:2024/05/16 17:00

做android开发还有面试的时候经验会遇到屏幕适配问题,Android由于机型太多,所以导致屏幕尺寸还有分辨率多样化.接下来讲解下DP、DPI、SP的概念,有些不对的地方欢迎指正

引用Andorid官方文档的说明

When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups.

所以关于适配主要根据手机屏幕大小和屏幕密度

什么是DPI

DPI(Dots Per Inch)表示屏幕密度,按字面意思理解就是每一英寸有多少个像素点,例如320DPI就表示一个Inch包含320个像素点.Android DPI也可以理解为PPI

一般我们说手机多少寸,是指手机屏幕对角线的长度,因此可以根据手机屏幕尺寸还有分辨率计算手机的DPI,比如MOTO X(1920*1080)、5.2英寸

DPI = Math.sqrt(1920*1920+1080*1080)/5.2

通过计算得出MOTO X的屏幕密度为424DPI

DP与PX的换算公式:

px = dp*(dpi/160)

也就是说如果要保持图片的大小统一,需要根据DPI提供不同的切图.
我们现在看下dp与英寸的关系,假设有一款手机Y也是5.2寸屏幕,分辨率是(1280*768),DPI计算后为287,由上面的公式可以计算出1dp对应多少英寸

Y = 1*(287/160)*(5.2/Math.sqrt(1280*1280+768*768))Y = 0.0062...

然后我们计算MOTO X 1dp对应多少英寸

MOTO X = 1*(424/160)*(5.2/Math.sqrt(1920*1920+1080*1080))MOTO X = 0.062...

通过上述我们可以得出一个结论dp可以保证所有设备大小的统一

假如项目里只提供一套切图

高DPI下图会被放大,低DPI下图会被缩小。

什么是SP

用于设置字体大小,因为手机可以设置大中小字体调整字体大小,所以特地设置的单位

TIPS之关于launcher图标

我们现在在studio新建项目的时候会发现在res底下多出一个mipmap的目录里面存放了APP的launcher图标,有人会疑惑有drawable不就行了为什么多了个这个文件夹,通过查官方文档大概了解了下,大概意思是部分设备会将launcher图标放大百分之25,这样会造成图标显示效果不够好,把图标放在mipmap目录下就会避免在不同的DPI下被删掉,这样android系统就可以在mipmap文件夹底下选择最优的Launcher icon显示在homescreen上。

Some devices scale-up the launcher icon by as much as 25%. For example, if your highest density launcher icon image is already extra-extra-high-density, the scaling process will make it appear less crisp. So you should provide a higher density launcher icon in the mipmap-xxxhdpi directory, which the system uses instead of scaling up a smaller version of the icon.

Different home screen launcher apps on different devices show app launcher icons at various resolutions. When app resource optimization techniques remove resources for unused screen densities, launcher icons can wind up looking fuzzy because the launcher app has to upscale a lower-resolution icon for display. To avoid these display issues, apps should use the mipmap/ resource folders for launcher icons. The Android system preserves these resources regardless of density stripping, and ensures that launcher apps can pick icons with the best resolution for display.

Make sure launcher apps show a high-resolution icon for your app by moving all densities of your launcher icons to density-specific res/mipmap/ folders (for example res/mipmap-mdpi/ and res/mipmap-xxxhdpi/). The mipmap/ folders replace the drawable/ folders for launcher icons. For xxhpdi launcher icons, be sure to add the higher resolution xxxhdpi versions of the icons to enhance the visual experience of the icons on higher resolution devices.

不同屏幕密度的参照图

参考了简书的某篇文章附链接

参考http://www.jianshu.com/p/913943d25829

0 0
原创粉丝点击