鸿蒙实战开发——获取屏幕宽高

2,239 阅读1分钟

首先,先说明一下鸿蒙中用到的单位

  • vp:虚拟像素。1vp 约等于 160dpi 屏幕密度设备上的 1px。
  • fp:字体像素。默认情况下与vp相同,但当用户在设置中修改了字体显示大小,那么字体大小则会在vp的基础上乘以 scale 系数。

获取方式如下:

        int width = getResourceManager().getDeviceCapability().width;
        int height = getResourceManager().getDeviceCapability().height;

注意,这里获取到的宽高的单位是vp,如果需要用到px,需要将vp转换成px。

鸿蒙提供了标准的转换工具,可通过如下方式转换

        System.out.println("输出高度:"+ AttrHelper.vp2px(height,this));
        System.out.println("输出宽度:"+AttrHelper.vp2px(width,this));