px与dp、sp之间的转换

我们在安卓开发时,往往需要在java代码中动态设置某个控件的大小(宽度和高度等),那么这个时候你会发现,设置的结果单位是px,但是我们还是想要dp或者sp,那这时候我们就得自己计算了。

下面是写好的帮助类,直接就可以去设置单位之间的转换:

 1 import android.content.Context;
 2 
 3 /**
 4  * Created by ws on 2016/3/4.
 5  */
 6 public class DisPlayUtil {
 7     /**
 8      * 将px值转换为dip或dp值,保证尺寸大小不变
 9      */
10     public static int px2dip(Context context, float pxValue) {
11         final float scale = context.getResources().getDisplayMetrics().density;
12         return (int) (pxValue / scale + 0.5f);
13     }
14 
15     /**
16      * 将dip或dp值转换为px值,保证尺寸大小不变
17      */
18     public static int dip2px(Context context, float dipValue) {
19         final float scale = context.getResources().getDisplayMetrics().density;
20         return (int) (dipValue * scale + 0.5f);
21     }
22 
23     /**
24      * 将px值转换为sp值,保证文字大小不变
25      */
26     public static int px2sp(Context context, float pxValue) {
27         final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
28         return (int) (pxValue / fontScale + 0.5f);
29     }
30 
31     /**
32      * 将sp值转换为px值,保证文字大小不变
33      */
34     public static int sp2px(Context context, float spValue) {
35         final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
36         return (int) (spValue * fontScale + 0.5f);
37     }
38 }

帮助类很简单,只是还需要传一个参数Context,那么谁调用他,就把谁作为参数传递到方法中,因为这里需要当前调用者的上下文场景。

小知识点需要日积月累(by四海小森森)

posted @ 2016-03-05 16:03  四海兴唐  阅读(728)  评论(0编辑  收藏  举报