写这篇的初衷是项目中总是遇到单位转换的问题,所以就想总结成一篇博客,这样我自己还有看到这篇博客的人就可以很方便的复制粘贴了。不多说了,我直接贴代码了,大家根据各自的需要选择吧
/**
* 将px值转换为dp值,保证尺寸不便。
* @param context
* @param pxValue
* @return
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue /scale + 0.5f);
}
/**
* 将dp值转换为px值,保持尺寸大小不变
* @param context
* @param dipValue
* @return
*/
public static int dip2px(Context context,float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
/**
* 将px值转换为dp值,保证尺寸不便。
* @param context
* @param pxValue
* @return
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int)(pxValue /fontScale + 0.5f);
}
/**
* 将dp值转换为px值,保持尺寸大小不变
* @param context
* @param spValue
* @return
*/
public static int sp2px(Context context,float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int)(spValue * fontScale + 0.5f);
}
//------------------------使用系统提供的TypedValue类进行转换--------------------
protected int dp2px(int dp,Context context) {
return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,context.getResources().getDisplayMetrics());
}
protected int sp2px(int sp,Context context) {
return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,sp,context.getResources().getDisplayMetrics());
}