Android根据分辨率进行单位转换-(dp,sp转像素px)

来源:互联网 发布:玛雅软件百度云 编辑:程序博客网 时间:2024/06/04 21:03

转载于: http://orgcent.com/android-dpsppx-unit-conversion/ | 萝卜白菜的博客

 

写的很好,特来笔记

 

 

Android系统中,默认的单位是像素(px)。也就是说,在没有明确说明的情况下,所有的大小设置都是以像素为单位。

如果以像素设置大小,会导致不同分辨率下出现不同的效果。那么,如何将应用中所有大小的单位都设置为’dp’呢?
实际上TextView.setTextSize()重载了根据单位设置大小的方法。

笔者在此基础上实现了以下方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 获取当前分辨率下指定单位对应的像素大小(根据设备信息)
* px,dip,sp -> px
*
* Paint.setTextSize()单位为px
*
* 代码摘自:TextView.setTextSize()
*
* @param unit  TypedValue.COMPLEX_UNIT_*
* @param size
* @return
*/

public float getRawSize(int unit,float size) {
       Context c = getContext();
       Resources r;

       if (c == null)
           r = Resources.getSystem();
       else
           r = c.getResources();
       
       return TypedValue.applyDimension(unit, size, r.getDisplayMetrics());
}

下面是网友提供的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/

public static int dip2px(Context context,float dpValue) {
  final float scale = context.getResources().getDisplayMetrics().density;
  return (int)(dpValue * scale + 0.5f);
}

/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/

public static int px2dip(Context context,float pxValue) {
  final float scale = context.getResources().getDisplayMetrics().density;
  return (int)(pxValue / scale + 0.5f);
}

 

原创粉丝点击