在鸿蒙中如何获取设备的宽度和高度?


在鸿蒙应用开发的过程中,需要用到屏幕的宽高,那么我们该如何获取手机屏幕的宽度和高度呢?另外,某个组件的父容器的宽高我们能不能获取到呢?带着这些问题,通过查找相关资料,结合实际的代码进行测试,顺利的获取到了屏幕宽高和父组件的宽高,下面一起来看一下具体该如何实现吧。

第一种方案

借助@ohos.display(屏幕属性)模块获取
具体代码如下:

import display from '@ohos.display';

@Entry
@Component
struct Index {
  @State deviceWidth: number = 0;
  @State deviceHeight: number = 0;

  build() {
    Column(){

    }.width('100%').height('100%')
  }

  aboutToAppear(): void {
    try {
      console.info('------>width:'+display.getDefaultDisplaySync().width)
      console.info('------>height:'+display.getDefaultDisplaySync().height)
      this.deviceWidth = display.getDefaultDisplaySync().width;
      this.deviceHeight = display.getDefaultDisplaySync().height;
    } catch (exception) {
      console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception))
    }
  }
}

第二种方案

通过最外层父组件的onAreaChange方法获取
具体代码如下:

@Entry
@Component
struct Index {
  @State deviceWidth: number = 0;

  build() {
    Column(){

    }.width('100%').height('100%')
    .onAreaChange((oldValue: Area, newValue: Area)=>{
      this.deviceWidth = new Number(newValue.width).valueOf();
    })
  }
}

参考文档

屏幕属性:
文档中心:屏幕属性
父组件宽高:
文档中心:组件区域变化事件

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐