Android单位转换 (px、dp、sp之间的转换工具类)
2016-11-13 14:36
465 查看
原文出自:http://blog.csdn.net/mouse12138/article/details/51249027
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
30
31
32
33
34
35
36
37
38
39
40
41
42
以上这是用公式转换方法进行转换。系统也提供了TypedValue帮助我们转换,代码如下:
package com.njxz.sy.deliverysystem.utils; import android.content.Context; /** * @创建时间:2016-1-4上午11:58:28 * @作者: SY * @描述信息:TODO */ public class DensityUtils { /** * 根据手机的分辨率从 dip 的单位 转成为 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); } /** * 将px值转换为sp值,保证文字大小不变 */ public static int px2sp(Context context, float pxValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (pxValue / fontScale + 0.5f); } /** * 将sp值转换为px值,保证文字大小不变 */ public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } }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
30
31
32
33
34
35
36
37
38
39
40
41
42
以上这是用公式转换方法进行转换。系统也提供了TypedValue帮助我们转换,代码如下:
protected int dp2px(int dp){ return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,dp, getResources().getDisplayMetrics()); } protected int sp2px(int sp){ return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP,sp, getResources().getDisplayMetrics()); }
相关文章推荐
- Android单位转换 (px、dp、sp之间的转换工具类)
- Android中常用单位dp,px,sp之间的相互转换
- Android中常用单位dp,px,sp之间的相互转换
- Android中常用单位dp,px,sp之间的相互转换
- Android中,单位dp、sp、px互相转换工具类
- Android工具类---dp,px,sp之间的转换
- Android 单位px、dp、sp转换工具类
- Android单位转换(px、sp、dp之间的转换)
- Android px、dp、sp之间相互转换
- 【Android技术】Android px、dp、sp之间相互转换
- Android根据分辨率进行单位转换-(dp,sp转像素px)
- Android中dip(dp)与px之间单位转换
- Android根据分辨率进行单位转换-(dp,sp转像素px)
- Android根据分辨率进行单位转换-(dp,sp转像素px)
- Android中dip(dp)与px之间单位转换
- Android px、dp、sp之间相互转换
- Android根据分辨率进行单位转换-(dp,sp转像素px)
- Android中常见的单位 dip, dp, px, sp之间的区别
- Android的计量单位px/dip/dp/sp/pt/in/mm,及相互转换
- Android px、dp、sp之间相互转换