HarmonyOS 如何获取顶部安全区域的高度?

目前在写布局时,遇到了一个问题,我们的上面是一个长方形图片,要顶到手机顶端,也就是覆盖到安全区域部分,代码如下:

Stack({ alignContent: Alignment.Top }) {

  Image($r('app.media.banner'))
    .width(this.deviceWidth)
    .height(this.bannerImageViewHeight)
    .margin({ top: 0, left: 0, right: 0 })// 设置顶部绘制延伸到状态栏
    .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])

  Column() {
    Image($r('app.media.logo'))
      .width(144)
      .height(27)
      .margin({ top: 100, left: 40 })

    Text('标题xxxxxxxx')
      .fontSize(14)
      .fontWeight(FontWeight.Bold)
      .fontColor('#333333')
      .margin({ top: 15, left: 40 })

  }.width('100%').margin({ top: 0 })
  // 主轴上的对齐方式
  .justifyContent(FlexAlign.Start)
  // 交叉轴上的对齐方式
  .alignItems(HorizontalAlign.Start)

  Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
    Button('按钮1')
      .width('100%')
      .height(48)
      .margin({ top: 0, left: 0 })
      .type(ButtonType.Normal)
      .borderRadius(10)
      .fontSize(18)
      .fontWeight(FontWeight.Bold)
      .fontColor(Color.Black)
      .backgroundColor(Color.White)
      .opacity(0.7)

    Button('按钮2')
      .width('100%')
      .height(48)
      .margin({ top: 0, left: 0})
      .type(ButtonType.Normal)
      .borderRadius(10)
      .fontSize(18)
      .fontWeight(FontWeight.Bold)
      .fontColor(Color.Black)
      .backgroundColor(Color.White)
      .opacity(0.7)

  }.padding({ top: this.bannerImageViewHeight - 48})

我们本来是要把这俩按钮盖到图片上面的,但是发现减去按钮高度48以后,按钮并没有全上去,有一半在底部的外面。所以肯定是顶部的安全区域的高度导致的,但我没有找到获取安全区域高度的API,没办法减去这个高度。所以这种情况应该怎么办?

阅读 507
1 个回答

当前window提供API获取系统区域包括导航栏和状态栏。

API:getWindowAvoidArea

window.getLastWindow(getContext(this), (error, topWindow) => {
  if (topWindow) {
    let area = topWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
    //注意:返回的是px值,如果要用vp值需要转换
    this.statusBarHeight = px2vp(area.topRect.height);
    this.naviBarHeight = px2vp(area.bottomRect.height);
  }
});

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-window-V5\#getwindowavoidarea9

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