Android中dip(dp)与px之间单位转换 dip2px dp转px 无context算法(以及获取获取屏幕宽度和高度)
16lz
2021-01-26
废话不多说直接上代码:
1.dip2px dp转px 无context算法
public static int px2dip(int pxValue){final float scale = Resources.getSystem().getDisplayMetrics().density;return (int) (pxValue / scale + 0.5f);}public static float dip2px(float dipValue){final float scale = Resources.getSystem().getDisplayMetrics().density;return (dipValue * scale + 0.5f);}
2.获取屏幕区域
/** * 获取屏幕区域 */ public static Rect getScreenRect() { DisplayMetrics displayMetric = new DisplayMetrics(); displayMetric = Resources.getSystem().getDisplayMetrics(); Rect rect = new Rect(0, 0, displayMetric.widthPixels, displayMetric.heightPixels); return rect; } /** * 获取屏幕宽度 * */ public static int getScreenWidth() { return getScreenRect().width(); } /** * 获取屏幕高度 * */ public static int getScreenHeight() { return getScreenRect().height(); }
更多相关文章
- Android(安卓)适配屏幕问题(一) 自动生成dimens文件
- 使用FileProvider共享文件
- getDrawable()缓存带来的问题
- Android中系统自带的锁:WalkLock、KeyguardLock
- android获取Mac地址和IP地址
- Android获取assets文件夹中的数据并写入SD卡示例
- Android核心分析(26)-----Android(安卓)GDI之SurfaceFlinger
- android将老项目改为按屏幕大小自适应,只需2步
- 解决android模拟器太大,小屏幕无法完全显示的问题