在HarmonyOS NEXT开发中怎么在Page中获取窗口的宽高?

在HarmonyOS NEXT开发中怎么在Page中获取窗口的宽高?不是设备的宽高,是要获取二分屏窗口大小,三分屏窗口大小,悬浮窗口大小

阅读 768
avatarAI BotBETA

在HarmonyOS NEXT中获取动态窗口尺寸(如二分屏、三分屏、悬浮窗),可通过以下两种核心方案实现:

方案一:窗口管理器监听(推荐)

import window from '@ohos.window';

@Entry
@Component
struct Index {
  @State windowWidth: number = 0
  @State windowHeight: number = 0

  aboutToAppear() {
    window.getLastWindow(this.context).then((win) => {
      // 初始获取
      win.getWindowProperties().then(props => {
        this.windowWidth = props.windowRect.width;
        this.windowHeight = props.windowRect.height;
      });

      // 注册窗口变化监听
      win.on('windowSizeChange', (rect) => {
        this.windowWidth = rect.width;
        this.windowHeight = rect.height;
      });
    });
  }
}

方案二:ArkUI布局回调

@Component
struct WindowSizeDisplay {
  @State winWidth: number = 0
  @State winHeight: number = 0

  build() {
    Column() {
      Text(`窗口尺寸:${this.winWidth}x${this.winHeight}`)
    }
    .onAreaChange((oldVal, newVal) => {
      this.winWidth = newVal.width;
      this.winHeight = newVal.height;
    })
  }
}

关键特性说明:

  1. 实时响应多窗口变化(分屏/悬浮窗调整时自动更新)
  2. 获取的是应用窗口实际可用区域尺寸(排除系统栏)
  3. 返回单位为vp,需配合屏幕密度计算像素值
  4. 支持全窗口模式:全屏、分屏(1/2、1/3)、悬浮窗(自由尺寸)

扩展应用场景:

// 自适应布局判断
if (this.windowWidth < 600) { // 600vp为折叠屏展开阈值
  // 手机布局
} else {
  // 平板/分屏布局
}

// 横竖屏检测
const isLandscape = this.windowWidth > this.windowHeight;

注意事项:

  • 需要在module.json5中添加权限:

    "requestPermissions": [
    "ohos.permission.GET_WINDOW_INFO"
    ]
  • 悬浮窗最小尺寸为150vp x 150vp
  • 分屏模式下窗口尺寸比例为1:1或1:2(二分屏)、1:2:1(三分屏)
1 个回答

试试窗口的getWindowproperties().windowRect()方法,然后就可以获取其width和height属性了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进