Android
主页 > 软件编程 > Android >

android中px、sp与dp之间进行转换介绍

2022-08-21 | 佚名 | 点击:

由于Android手机厂商很多,导致了不同设备屏幕大小和分辨率都不一样,然而我们开发者要保持在不同设备上显示同样的视觉效果,就需要做一些适配效果。

相关名词解释

系统屏幕密度

由于各种屏幕密度的不同,导致了同一张图片在不同的手机屏幕上显示不同;在屏幕大小相同的情况下,高密度的屏幕包含了更多的像素点。android系统将密度为160dpi的屏幕作为标准对于mdpi文件夹,在此屏幕的手机上1dp=1px。从上面系统屏幕密度可以得出各个密度值之间的换算;在mdpi中1dp=1px,在hdpi中1dp=1.5px,在xhdpi中1dp=2px,在xxhpi中1dp=3px。换算比例如下:ldpi:mdpi:hdpi:xhdpi:xxhdpi=3:4:6:8:12。

单位换算方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

/**

     * dp转换成px

     */

    private int dp2px(Context context,float dpValue){

        float scale=context.getResources().getDisplayMetrics().density;

        return (int)(dpValue*scale+0.5f);

    }

 

    /**

     * px转换成dp

     */

    private int px2dp(Context context,float pxValue){

        float scale=context.getResources().getDisplayMetrics().density;

        return (int)(pxValue/scale+0.5f);

    }

    /**

     * sp转换成px

     */

    private int sp2px(Context context,float spValue){

        float fontScale=context.getResources().getDisplayMetrics().scaledDensity;

        return (int) (spValue*fontScale+0.5f);

    }

    /**

     * px转换成sp

     */

    private int px2sp(Context context,float pxValue){

        float fontScale=context.getResources().getDisplayMetrics().scaledDensity;

        return (int) (pxValue/fontScale+0.5f);

    }

利用系统TypeValue类来转换

1

2

3

4

5

6

private int dp2px(Context context,int dpValue){

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpValue,context.getResources().getDisplayMetrics());

    }

    private int sp2px(Context context,int spValue){

        return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,spValue,context.getResources().getDisplayMetrics());

    }

补充:sp与dp的区别

下面我们进行一下实验: textSize的单位分别设置为sp和dp,然后改变系统字体大小

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

  

    <TextView

        android:layout_width="200dp"

        android:layout_height="wrap_content"

        android:text="尚硅谷科技"

        android:background="#ff0000"

        android:textSize="20sp"/>

  

    <TextView

        android:id="@+id/textView2"

        android:layout_width="200px"

        android:layout_height="wrap_content"

        android:text="尚硅谷科技"

        android:background="#00ff00"

        android:textSize="20dp"/>

  

</LinearLayout>

1、用sp做单位,设置有效果

2、dp做单位没有效果

原文链接:https://blog.csdn.net/qidingquan/article/details/53714603
相关文章
最新更新