一个Android工具类,px转dp等
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);
}
public static int pt2dip(float ptValue, float fontScale, float density) {
return px2dip((ptValue / 72) * density, fontScale);
}
public static int pt2sp(float ptValue, float fontScale, float density) {
return px2sp((ptValue / 72) * density, fontScale);
}
public static int pt2px(float ptValue, float density) {
return (int) (ptValue / 72 * density);
}
/**
* 将sp值转换为px值,保证文字大小不变
*
* @param spValue
* @param fontScale (DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int sp2px(float spValue, float fontScale) {
return (int) (spValue * fontScale + 0.5f);
}
public static int getVisibleHeight(Activity activity) {
return activity.getWindowManager().getDefaultDisplay().getHeight()
- getStatusHeight(activity);
}
public static int getStatusHeight(Activity activity) {
int statusHeight = 0;
Rect localRect = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
statusHeight = localRect.top;
if (0 == statusHeight) {
Class<?> localClass;
try {
localClass = Class.forName("com.android.internal.R$dimen");
Object localObject = localClass.newInstance();
int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject)
.toString());
statusHeight = activity.getResources().getDimensionPixelSize(i5);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return statusHeight;
}
}