您的位置:首页 > 移动开发 > Android开发

Android单位转换 (px、dp、sp之间的转换工具类)

2016-11-13 14:36 465 查看
原文出自:http://blog.csdn.net/mouse12138/article/details/51249027

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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: