HarmonyOS鸿蒙Next中如何获取窗口的宽高信息

HarmonyOS鸿蒙Next中如何获取窗口的宽高信息 如何获取窗口的宽高信息

3 回复
import window from '@ohos.window';
let windowClass = null;
try {    
    let promise = window.getLastWindow(this.context);
    promise.then((data) => {
        //获取窗口对象
        windowClass = data;
        try {
            //获取窗口属性
            let properties = windowClass.getWindowProperties();
            let rect = properties.windowRect;
            //rect.width: 窗口宽度;rect.height: 窗口高度
        } catch (exception) {
             console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception));
        }
        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
    }).catch((err) =>{
        console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
    });
} catch (exception) {
    console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
}

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


在HarmonyOS鸿蒙Next中,获取窗口的宽高信息可以通过Window类实现。Window类提供了getWindowWidth()getWindowHeight()方法,分别用于获取窗口的宽度和高度。以下是一个简单的示例代码:

import window from '@ohos.window';

// 获取当前窗口
let windowClass = await window.getLastWindow(this.context);

// 获取窗口的宽度和高度
let width = windowClass.getWindowWidth();
let height = windowClass.getWindowHeight();

这段代码中,window.getLastWindow(context)用于获取当前窗口的实例,然后通过getWindowWidth()getWindowHeight()方法获取窗口的宽高信息。确保在代码中正确传递context参数以获取窗口实例。

在HarmonyOS鸿蒙Next中,可以通过Window类来获取窗口的宽高信息。首先,使用WindowManager获取当前窗口对象,然后调用getBounds()方法获取窗口的边界信息,最后通过Rect对象获取宽高。示例代码如下:

WindowManager windowManager = getWindowManager();
Window window = windowManager.getDefaultDisplay();
Rect bounds = window.getBounds();
int width = bounds.width();
int height = bounds.height();

这样即可获取当前窗口的宽高信息。

回到顶部