HarmonyOS鸿蒙Next中如何获得windowSize

HarmonyOS鸿蒙Next中如何获得windowSize,getContext出来的UIAbilityContext中的windowSize都为0

4 回复

可以通过获取window的properties,创建窗口实例调用getWindowProperties()

可参考如下链接: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-window-V5#windowproperties

更多关于HarmonyOS鸿蒙Next中如何获得windowSize的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


0 0 可以获取窗口的

import display from '@ohos.display'

display.getDefaultDisplaySync().width
...

在HarmonyOS鸿蒙Next中,可以通过Window类的getWindowSize方法来获取窗口大小。具体代码如下:

import window from '@ohos.window';

let windowClass = window.getLastWindow(this.context);
windowClass.getWindowSize().then(size => {
    console.log(`Window width: ${size.width}, height: ${size.height}`);
});

getWindowSize返回一个Promise,解析后包含窗口的宽度和高度。

在HarmonyOS Next中获取正确的windowSize,可以使用Window类的getWindowProperties()方法。当UIAbilityContext返回的windowSize为0时,通常是因为窗口尚未完成初始化。

推荐解决方案:

  1. 在UIAbility的onWindowStageCreate回调中获取:
onWindowStageCreate(windowStage: window.WindowStage) {
    let windowClass = windowStage.getMainWindow()
    windowClass.getWindowProperties().then(properties => {
        console.log(`Window size: ${properties.windowRect.width}x${properties.windowRect.height}`)
    })
}
  1. 或者在页面中使用@ohos.window模块:
import window from '@ohos.window'

let windowClass = await window.getLastWindow(this.context)
let properties = await windowClass.getWindowProperties()
console.log(`Window size: ${properties.windowRect.width}x${properties.windowRect.height}`)

注意要在config.json中申请ohos.permission.SYSTEM_FLOAT_WINDOW权限。

回到顶部