纯血鸿蒙APP实战开发——适配挖孔屏案例

介绍

本示例介绍使用屏幕属性 getDefaultDisplaySync、getCutoutInfo 接口实现适配挖孔屏。该场景多用于沉浸式场景下。

效果图预览

使用说明

  1. 加载完成后顶部状态栏时间和电量显示位置规避了不可用区域。

实现思路

  1. 通过setWindowLayoutFullScreen、setWindowSystemBarEnable将窗口设置为全屏,并且隐藏顶部状态栏。源码参考DiggingHoleScreen.ets
// 获取窗口实例
window.getLastWindow(this.context, (err, data) => {
  if (err) {
    logger.error('DiggingHoleScreen', 'getLastWindow failed. error is:', JSON.stringify(err));
    return;
  }
  // 设置窗口为全屏显示状态
  data.setWindowLayoutFullScreen(true);
  // 设置顶部状态栏为隐藏状态
  data.setWindowSystemBarEnable(['navigation']);
  });
  1. 通过getDefaultDisplaySync、getCutoutInfo获取窗口display对象和不可用区域的边界、宽高。源码参考DiggingHoleScreen.ets
this.displayClass = display.getDefaultDisplaySync();
this.displayClass.getCutoutInfo((err, data) => {
  if (err) {
    logger.error('DiggingHoleScreen', 'getCutoutInfo failed. error is:', JSON.stringify(err));
    return;
  }
  this.boundingRect = data.boundingRects;
  this.topTextMargin = this.getBoundingRectPosition();
  });
  1. 使用获取到的信息进行计算偏移量实现对不可用区域的适配。源码参考DiggingHoleScreen.ets
getBoundingRectPosition(): TextMargin {
  if (this.boundingRect !== null && this.displayClass !== null && this.boundingRect[0] !== undefined) {
    // 不可用区域右侧到屏幕右边界的距离:屏幕宽度减去左侧宽度和不可用区域宽度
    let boundingRectRight: number = this.displayClass.width - (this.boundingRect[0].left + this.boundingRect[0].width);
    // 不可用区域左侧到屏幕左边界的距离:getCutoutInfo接口可以直接获取
    let boundingRectLeft: number = this.boundingRect[0].left;
    // 部分设备不可用区域在中间时存在左右距离会有10像素以内的差距,获取到的左右距离差值绝对值小于10都按照不可用区域位于中间处理
    if (Math.abs(boundingRectLeft - boundingRectRight) <= 10) {
      return { left: 0, right: 0 };
    }
    if (boundingRectLeft > boundingRectRight) {
      // 不可用区域在右边
      return { left: 0, right: this.displayClass.width - boundingRectLeft };
    } else if (boundingRectLeft < boundingRectRight) {
      // 不可用区域在左边
      return { left: this.boundingRect[0].left + this.boundingRect[0].width, right: 0 };
    }
  }
  return { left: 0, right: 0 };
}
高性能知识点

不涉及

工程结构&模块类型

   functionalscenes                                // har类型(默认使用har类型,如果使用hsp类型请说明原因)
   |---mainpage
   |   |---DigginHoleScreen.ets                    // 挖孔屏适配页面

写在最后

如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙

  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。
  • 想要获取更多完整鸿蒙最新学习知识点,请移步前往小编:https://gitee.com/MNxiaona/733GH

在这里插入图片描述

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值