Android开发中布局与组件(一)—— 屏幕尺寸单位dp,px,sp的探究

在Android开发中,常用的尺寸单位有 dp , px , sp 。当然还有其他的单位如 pt , mm 等,不过这些都是不常用,所以我们重点来探究一下 dp , px , sp 这三个常用的单位。

  • px
    英文 pixel 的缩写,即像素。无论屏幕密度为多少,一个像素单位对应屏幕上的一个像素,因此在 android开发中 并不推荐使用 px 为单位,因为它在不同分辨率的屏幕上显示的效果差别很大。
  • dp(或dip)
    英文 density-independent pixel 的缩写,意思为密度无关像素,可以把它理解为一个物理尺寸,即不管在什么分变率的屏幕上表现出的大小都是一致的,所以在设定视图尺寸的时候,推荐以 dp 座位视图的单位。
  • sp 英文 scale-independent pixel 的缩写,意思是与缩放无关的像素。它也是一种与密度无关的像素。通常使用 sp 作为字体大小的单位。

了解了这三种的单位的不同,我们来看看在实际应用中它们的效果:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Text size is 30px"
        android:textSize="30px"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Text size is 30dp"
        android:textSize="30dp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Text size is 30sp"
        android:textSize="30sp"/>


</LinearLayout>

在上面的代码中我们定义了三个分别使用不同单位的 TextView ,我们来看看在不同分辨率下它们的表现如何:

由上图可见, 以 dp 为单位的字体,无论在什么情况下表现的大小都相同,以 px 为单位的字体在不同分辨率下表现的大小不同,在高分辨率的屏幕上表现的更小一些,在低分辨率的屏幕上表现的更大一些。以 sp 为单位的字体只会随系统设置中字体的大小做一定的改变,而与屏幕的分辨率也没有关系。

希望可以帮到对尺寸的单位有疑惑的朋友。

PS:开发了一个制作个性二维码的应用,有兴趣的朋友可以试一试~ 创意二维码制作

猜你喜欢

转载自blog.csdn.net/ToBeTheOnlyOne/article/details/79320728