dp 与 sp 区别

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 screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".



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 user’s preference.


和字体相关最好用sp




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Android 设备上,像素(Pixel)是指显示屏上的最小颜色点,而 dpsp、px 则用于描述在不同分辨率的设备上,一个视觉元素的尺寸和位置。 - dp(density-independent pixels):密度无关像素。是一种基于屏幕密度的抽象单位,它可以让布局在不同的设备上有相同的显示效果。1dp 对应的像素数取决于设备的屏幕密度。通常,在设计 UI 时应使用 dp 单位。 - sp(scale-independent pixels):与 dp 类似,但用于描述文字大小。与 dp 不同的是,用户可以在系统设置中调整字体大小,因此 sp 的值会随着用户在系统设置中的调整而发生变化。 - px(pixels):像素。是屏幕上的最小显示单位,1px 对应一个实际的像素点。在设计 UI 时,应该尽量避免使用 px,因为在不同分辨率的设备上会导致 UI 显示效果不一致。 在布局文件中,可以使用 dpsp 单位来设置视觉元素的尺寸和位置,例如: ``` <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:padding="8dp" android:text="Hello, world!" /> ``` 在代码中,可以使用以下方法将 dpsp 转换为 px: ``` // 将 dp 转换为 px int px = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()); // 将 sp 转换为 px int px = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值