在java代码中进行px与dip(dp)、px与sp单位值的转换(转)------工具类

andorid中常用的长度单位--------------很好的东西,收藏了,谢谢原创分享。

px,dp,sp之间相互转换的工具 


/**
 * 单位转换工具
 * 
 * @author carrey
 * 
 */
public class DisplayUtil {
	/**
	 * 将px值转换为dip或dp值,保证尺寸大小不变
	 * 
	 * @param pxValue
	 * @param scale
	 *            (DisplayMetrics类中属性density)
	 * @return
	 */
	public static int px2dip(float pxValue, float scale) {
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 将dip或dp值转换为px值,保证尺寸大小不变
	 * 
	 * @param dipValue
	 * @param scale
	 *            (DisplayMetrics类中属性density)
	 * @return
	 */
	public static int dip2px(float dipValue, float scale) {
		return (int) (dipValue * scale + 0.5f);
	}

	/**
	 * 将px值转换为sp值,保证文字大小不变
	 * 
	 * @param pxValue
	 * @param fontScale
	 *            (DisplayMetrics类中属性scaledDensity)
	 * @return
	 */
	public static int px2sp(float pxValue, float fontScale) {
		return (int) (pxValue / fontScale + 0.5f);
	}

	/**
	 * 将sp值转换为px值,保证文字大小不变
	 * 
	 * @param spValue
	 * @param fontScale
	 *            (DisplayMetrics类中属性scaledDensity)
	 * @return
	 */
	public static int sp2px(float spValue, float fontScale) {
		return (int) (spValue * fontScale + 0.5f);
	}
}


屏幕参数工具类,得到屏幕的宽度,高度,密度,洗漱,缩放系数,屏幕朝向

/**
 * 屏幕参数工具
 * 
 * @author carrey
 * 
 */
public class DisplayParams {
	/** 屏幕宽度——px */
	public int screenWidth;
	/** 屏幕高度——px */
	public int screenHeight;
	/** 屏幕密度——dpi */
	public int densityDpi;
	/** 缩放系数——densityDpi/160 */
	public float scale;
	/** 文字缩放系数 */
	public float fontScale;
	/** 屏幕朝向 */
	public int screenOrientation;
	/** 表示屏幕朝向垂直 */
	public final static int SCREEN_ORIENTATION_VERTICAL = 1;
	/** 表示屏幕朝向水平 */
	public final static int SCREEN_ORIENTATION_HORIZONTAL = 2;

	private static DisplayParams singleInstance;

	/**
	 * 私有构造方法
	 * 
	 * @param context
	 */
	private DisplayParams(Context context) {
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		screenWidth = dm.widthPixels;
		screenHeight = dm.heightPixels;
		densityDpi = dm.densityDpi;
		scale = dm.density;
		fontScale = dm.scaledDensity;
		screenOrientation = screenHeight > screenWidth ? SCREEN_ORIENTATION_VERTICAL
				: SCREEN_ORIENTATION_HORIZONTAL;
	}

	/**
	 * 获取实例
	 * 
	 * @param context
	 * @return
	 */
	public static DisplayParams getInstance(Context context) {
		if (singleInstance == null) {
			singleInstance = new DisplayParams(context);
		}
		return singleInstance;
	}

	/**
	 * 获取新的实例
	 * 
	 * @param context
	 * @return
	 */
	public static DisplayParams getNewInstance(Context context) {
		if (singleInstance != null) {
			singleInstance = null;
		}
		return getInstance(context);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值