HarmonyOS 鸿蒙Next关于屏幕高度

发布于 1周前 作者 sinazl 来自 鸿蒙OS

HarmonyOS 鸿蒙Next关于屏幕高度

display.getDefaultDisplaySync 可以获取到整个屏幕的高度,
那顶部的状态栏和底部的安全区高度 怎么获取?

4 回复

可以在EntryAbility里获取并存储,获取到的高度是px,所以用px2vp()转换为vp使用:

onWindowStageCreate(windowStage: window.WindowStage) {
  // Main window is created, set main page for this ability
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

  windowStage.loadContent('pages/Index', (err, data) => {
    if (err.code) {
      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');

    let windowClass = windowStage.getMainWindowSync();
    let statusHeight = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM).topRect.height;
    let bottomHeight = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR).bottomRect.height;
    AppStorage.setOrCreate('bottomHeight',px2vp(bottomHeight));
    AppStorage.setOrCreate('statusHeight',px2vp(statusHeight));
  });
}

在需要的界面使用 AppStorage.get(‘bottomHeight’),AppStorage.get(‘statusHeight’) 获取。

更多关于HarmonyOS 鸿蒙Next关于屏幕高度的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next系统中,获取屏幕高度通常涉及到访问系统的显示服务或窗口管理服务。以下是直接获取屏幕高度的方法,不涉及Java或C语言代码:

HarmonyOS提供了丰富的系统API供开发者使用,其中与屏幕高度相关的信息可以通过WindowMetrics或类似的类获取(注意,具体类名和方法可能随版本更新而变化,以下示例为假设性描述)。

  1. 使用系统服务: 通过系统服务接口,可以查询当前显示设备的屏幕信息。例如,通过DisplayMetrics对象(或等效的HarmonyOS对象),可以获取屏幕的高度和宽度。

  2. 窗口管理: 如果应用需要获取当前窗口的高度,可以通过窗口管理接口获取窗口的布局参数,其中包含了窗口的高度信息。

  3. 直接访问显示属性: 在某些情况下,可以直接访问系统的显示属性,这些属性包含了屏幕的分辨率和物理尺寸,通过计算可以得到屏幕高度。

示例代码(伪代码,具体实现需参考HarmonyOS SDK文档):

DisplayMetrics metrics = getWindowManager().getDefaultDisplay().getRealMetrics();
int screenHeight = metrics.heightPixels;

注意:上述代码为示例性描述,实际开发中需根据HarmonyOS提供的API进行调整。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!