当前位置: 首页 > news >正文

Android 获取屏幕物理尺寸

注:编译 sdk 需要使用 30

因为引入了 WindowMetrics、uild.VERSION_CODES.R 新 sdk 才存在的类和属性

某些场景处理 view ,对 view 显示的位置要求比较精确,通常我们使用context.getResources().getDisplayMetrics().widthPixels 获取到的宽、高是不包含状态栏等高度,在计算坐标、偏移量时可能就不精确了,那么就需要获取设备的物理尺寸——包含状态栏高度等不显示区域。

import android.graphics.Point;
import android.graphics.Rect;
import android.util.Pair;
import android.util.Size;
import android.view.WindowManager;
import android.view.WindowMetrics;import androidx.annotation.RequiresApi;@RequiresApi(api = Build.VERSION_CODES.R)
private static Size getPhysicalScreenSize30(Context context) {WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);if (windowManager != null) {WindowMetrics windowMetrics = windowManager.getCurrentWindowMetrics();Rect bounds = windowMetrics.getBounds();return new Size(bounds.width(), bounds.height());}return new Size(-1,-1);
}@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static Size getPhysicalScreenSize29(Context context) {WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);if (windowManager != null) {Point size = new Point();windowManager.getDefaultDisplay().getRealSize(size);return new Size(size.x, size.y);}return new Size(-1,-1);
}public static Pair<Integer, Integer> getPhysicalScreenSize(Context context) {int w = -1, h = -1;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {Size size = getPhysicalScreenSize30(context);w = size.getWidth();h = size.getHeight();} else {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {Size size = getPhysicalScreenSize29(context);w = size.getWidth();h = size.getHeight();}}if (w != -1 && h != -1) {return new Pair<>(w, h);}//最不济的情况就返回非物理尺寸吧w = context.getResources().getDisplayMetrics().widthPixels;h = context.getResources().getDisplayMetrics().heightPixels;return new Pair<>(w, h);
}
http://www.lryc.cn/news/506636.html

相关文章:

  • C缺陷与陷阱 — 8 编译与链接
  • 知识分享第三十天-力扣343.(整数拆分)
  • Springboot 整合DL4J 打造智能写作助手(文本生成)
  • SPL06 基于stm32F103 HAL库驱动(软件模拟IIC)
  • 【C#】List求并集、交集、差集
  • YOLOv8目标检测——详细记录使用ONNX Runtime进行推理部署C++/Python实现
  • mfc140u.dll是什么文件?如何解决mfc140u.dll丢失的相关问题
  • Redis篇-19--运维篇1-主从复制(主从复制,读写分离,配置实现,实战案例)
  • 【Elasticsearch入门到落地】4、Elasticsearch的安装
  • 计算无人机俯拍图像的地面采样距离(GSD)矩阵
  • 牛客网 SQL37查找多列排序
  • el-tabs标签过多
  • 如何制作搞笑配音视频?操作方法
  • [Unity]Unity跨平台开发之针对Android开发
  • ELK部署
  • ELK系列-(四)轻量级的日志收集助手-Beat家族
  • NodeJs-包管理工具
  • AWR microwave office 仿真学习(二)使用多层结构天线/超表面的S参数确定层间距
  • 【zlm】 webrtc源码讲解三(总结)
  • Springboot+Druid(可切换Hikari)+Mybatis-plus+mysql+hive的多数据源项目配置
  • Git使用步骤
  • Python+OpenCV系列:AI看图识人、识车、识万物
  • springboot449教学资源共享平台(论文+源码)_kaic
  • 类OCSP靶场-Kioptrix系列-Kioptrix Level 4
  • 贪心算法在背包问题上的运用(Python)
  • POD 存储、PV、PVC
  • C中strlen和sizeof的区别
  • WSL2内部的Ubuntu怎么设置网络内桥接模式,弄了好久老是不成功,怎么办?
  • Linux环境下 搭建ELk项目 -单机版练习
  • ubuntu20.04安装mysql5.7