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

使用說明
- 加載完成后頂部狀態(tài)欄時間和電量顯示位置規(guī)避了不可用區(qū)域。
實(shí)現(xiàn)思路
- 通過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']);
});
- 通過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();
});
- 使用獲取到的信息進(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 // 挖孔屏適配頁面