虚拟像素单位, 用于定义应用的UI, 以密度无关的方式表达布局尺寸或位置.
android官方定义dip等价于160dpi屏幕下的一个物理像素点.
在运行时, android根据使用中的屏幕的实际密度, 透明地处理任何所需dp单位的缩放.
dp到屏幕像素的转换公式: pixels = dps * (density / 160).
举例来说, 在 240 dpi 的屏幕上, 1dp 等于 1.5物理像素.
强烈推荐使用dp单位来定义你的应用UI, 这是确保你的UI在不同屏幕上显示的一个好方法.
- Android平台划分几个的实际支持的屏幕尺寸和分辨率范围
- 4个通用尺寸:
- small: 至少
426dp x 320dp - normal: 至少
470dp x 320dp - large: 至少
640dp x 480dp - xlarge: 至少 960dp x 720dp --
Android 2.3 (API Level 9)
- small: 至少
- 4个通用屏幕密度:
- ldpi (low)
- mdpi (medium)
- hdpi (high)
- xhdpi (extra high): --
Android 2.2 (API Level 8)
- 4个通用尺寸:
图1:
表 1. Android SDK中包含的模拟器皮肤的屏幕尺寸和密度,以及其他典型的分辨率.
| Size | Low density (120), ldpi | Medium density (160), mdpi | High density (240), hdpi | Extra high density (320), xhdpi |
---|---|---|---|---|---|
Small screen | 2 ~ | QVGA (240x320) | | 480x640 | |
Normal screen | 3+ ~ 4.5 inch | WQVGA400 (240x400) WQVGA432 (240x432) | HVGA (320x480) | WVGA800 (480x800) WVGA854 (480x854) 600x1024 | 640x960 |
Large screen | 4+ | WVGA800** WVGA854** | WVGA800* (480x800) WVGA854* (480x854) 600x1024 | | |
Extra Large screen | 7 | 600x1024 | 768x1024 WXGA (768x1280) 800x1280 | 1152x1536 1152x1920 1200x1920 | 1536x2048 1536x2560 1600x2560 |
* 要模拟此配置, 使用WVGA800 或 WVGA854创建一个AVD, 指定自定义密度160.
** 要模拟此配置, 使用WVGA800 或 WVGA854创建一个AVD, 指定自定义密度120.
ps: 增加辅助工具类:
- import
android.content.Context; -
- public
class DensityUtil { -
-
-
public static int dip2px(Context context, float dpValue) { -
final float scale = context.getResources().getDisplayMetrics().density; -
return (int) (dpValue * scale + 0.5f); -
} -
-
-
public static int px2dip(Context context, float pxValue) { -
final float scale = context.getResources().getDisplayMetrics().density; -
return (int) (pxValue / scale + 0.5f); -
} - }