我们做屏幕适配的时候,经常需要获取屏幕的宽度,高度,单位转换这几个方法,代码如下:
public class ScreenUtil {
private ScreenUtil() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 获取配屏幕宽度
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point p = new Point();
wm.getDefaultDisplay().getSize(p);
return p.x;
}
/**
* 获取屏幕的高度
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point p = new Point();
wm.getDefaultDisplay().getSize(p);
return p.y;
}
/**
* dp 转 px
* @param context
* @param dpValue
* @return
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 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);
}
/**
* sp 转 px
* @param context
* @param spValue
* @return
*/
public static int sp2px(Context context, float spValue) {
final float scale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * scale + 0.5f);
}
/**
* px 转 sp
* @param context
* @param pxValue
* @return
*/
public static int px2sp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / scale + 0.5f);
}
}
网友评论