Android 获取屏幕宽高,dp、px、sp互转
在Android日常开发中,我们肯定都要做界面适配,这时候我们可能会需要知道屏幕的宽高和常用单位之间的转换,下面我们一起来看看,宽高如何获取,常用单位之间如何转换的。
1、获取屏幕宽高
代码如下:
/**
* 获取屏幕的Size
*
* @return point.x:屏幕宽度 point.y:屏幕高度
*/
public static Point getScreenSize(Context context) {
WindowManager manager = getSystemService(Context.WINDOW_SERVICE);
if (manager == null) {
return new Point();
}
Display display = manager.getDefaultDisplay();
Point p = new Point();
display.getSize(p);
Configuration config = context.getResources().getConfiguration();
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 横屏
return new Point(Math.max(p.x, p.y), Math.min(p.x, p.y));
} else {
// 竖屏
return new Point(Math.min(p.x, p.y), Math.max(p.x, p.y));
}
}
通过上面的代码我们就可以获取到手机屏幕的宽高了,同时还自动为我们区分了横竖屏时的宽高。
2、dp转化为px
代码如下:
public static float dip2px(Context context, float dp) {
Resources res = context.getResources();
float density = res.getDisplayMetrics().density;
return dp * density + 0.5f;
}
3、px转化为dp
代码如下:
public static float px2dp(Context context, float px) {
Resources res = context.getResources();
float density = res.getDisplayMetrics().density;
return px / density + 0.5f;
}
4、sp转化为px
public static float sp2px(Context context, float sp) {
Resources res = context.getResources();
float density = res.getDisplayMetrics().density;
return sp * density;
}