HarmonyOS NEXT應(yīng)用開發(fā)之適配挖孔屏案例

介紹

本示例介紹使用屏幕屬性getDefaultDisplaySync、getCutoutInfo接口實(shí)現(xiàn)適配挖孔屏。該場景多用于沉浸式場景下。

效果圖預(yù)覽

使用說明

  1. 加載完成后頂部狀態(tài)欄時間和電量顯示位置規(guī)避了不可用區(qū)域。

實(shí)現(xiàn)思路

  1. 通過setWindowLayoutFullScreen、setWindowSystemBarEnable將窗口設(shè)置為全屏,并且隱藏頂部狀態(tài)欄。源碼參考DiggingHoleScreen.ets
// 獲取窗口實(shí)例
window.getLastWindow(this.context, (err, data) => {
  if (err) {
    logger.error('DiggingHoleScreen', 'getLastWindow failed. error is:', JSON.stringify(err));
    return;
  }
  // 設(shè)置窗口為全屏顯示狀態(tài)
  data.setWindowLayoutFullScreen(true);
  // 設(shè)置頂部狀態(tài)欄為隱藏狀態(tài)
  data.setWindowSystemBarEnable(['navigation']);
  });
  1. 通過getDefaultDisplaySync、getCutoutInfo獲取窗口display對象和不可用區(qū)域的邊界、寬高。源碼參考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. 使用獲取到的信息進(jìn)行計(jì)算偏移量實(shí)現(xiàn)對不可用區(qū)域的適配。源碼參考DiggingHoleScreen.ets
getBoundingRectPosition(): TextMargin {
  if (this.boundingRect !== null && this.displayClass !== null && this.boundingRect[0] !== undefined) {
    // 不可用區(qū)域右側(cè)到屏幕右邊界的距離:屏幕寬度減去左側(cè)寬度和不可用區(qū)域?qū)挾?    let boundingRectRight: number = this.displayClass.width - (this.boundingRect[0].left + this.boundingRect[0].width);
    // 不可用區(qū)域左側(cè)到屏幕左邊界的距離:getCutoutInfo接口可以直接獲取
    let boundingRectLeft: number = this.boundingRect[0].left;
    // 部分設(shè)備不可用區(qū)域在中間時存在左右距離會有10像素以內(nèi)的差距,獲取到的左右距離差值絕對值小于10都按照不可用區(qū)域位于中間處理
    if (Math.abs(boundingRectLeft - boundingRectRight) <= 10) {
      return { left: 0, right: 0 };
    }
    if (boundingRectLeft > boundingRectRight) {
      // 不可用區(qū)域在右邊
      return { left: 0, right: this.displayClass.width - boundingRectLeft };
    } else if (boundingRectLeft < boundingRectRight) {
      // 不可用區(qū)域在左邊
      return { left: this.boundingRect[0].left + this.boundingRect[0].width, right: 0 };
    }
  }
  return { left: 0, right: 0 };
}

高性能知識點(diǎn)

不涉及

工程結(jié)構(gòu)&模塊類型

functionalscenes                                // har類型(默認(rèn)使用har類型,如果使用hsp類型請說明原因)
|---mainpage
|   |---DigginHoleScreen.ets                    // 挖孔屏適配頁面

模塊依賴

  1. 路由模塊:供entry模塊實(shí)現(xiàn)路由導(dǎo)航
  2. utils模塊:功能介紹

參考資料

@ohos.display (屏幕屬性)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容