【关键字】
px2vp像素单位转换 / @ohos.app.ability.UIAbility组件 / @ohos.window (窗口)模块 / windowStage.loadContent
【问题描述】
通过getWindowAvoidArea.topRect.heigth获取到状态栏的高度为126,这个高度设置为组件的margintop,在工具类里面通过px2vp 126 = 126, 而在component中转换后得到的值却不一样,是什么原因?
screenutils(hsp): 在entryablity中的onWindowCreate中初始化:
import window from '@ohos.window';
import { LogUtils } from './LogUtils';
import { DS_COMPONENTS_TAG } from '../DSComponentsContants';
export class ScreenUtils {
private static TAG: string = `${DS_COMPONENTS_TAG}-${ScreenUtils.name}`
private static _statusBarHeight: number = 0
private static _navigationBarHeight: number = 0
private static _screenWidth: number = 0
private static _screenHeight: number = 0
private static _contentHeight: number = 0
private static _contentWidth: number = 0
static get statusBarHeight(): number {
return ScreenUtils._statusBarHeight
}
static get navigationBarHeight(): number {
return ScreenUtils._navigationBarHeight
}
static get screenWidth(): number {
return ScreenUtils._screenWidth
}
static get screenHeight(): number {
return ScreenUtils._screenHeight
}
static get contentHeight(): number {
return ScreenUtils._contentHeight
}
static get contentWidth(): number {
return ScreenUtils._contentWidth
}
static async init(windowStage: window.WindowStage): Promise<boolean> {
let windowClass: window.Window | null = await windowStage.getMainWindowSync()
let type = window.AvoidAreaType.TYPE_SYSTEM;
try {
let area = windowClass.getWindowAvoidArea(type);
ScreenUtils._statusBarHeight = px2vp(area.topRect.height)
ScreenUtils._navigationBarHeight = px2vp(area.bottomRect.height)
ScreenUtils._screenWidth = px2vp(area.topRect.width)
ScreenUtils._contentWidth = px2vp(area.topRect.width)
ScreenUtils._screenHeight = px2vp(area.bottomRect.height + area.bottomRect.top)
ScreenUtils._contentHeight = px2vp(area.bottomRect.top - ScreenUtils._statusBarHeight)
if (area.bottomRect.height == 0) {
ScreenUtils._screenHeight = px2vp(windowClass.getWindowProperties().windowRect.height)
ScreenUtils._contentHeight = px2vp(windowClass.getWindowProperties().windowRect.height)
}
}
【解决方案】
px2vp是ArkUI的接口。初始化ArkUI之前,转化比例是1,只有当初始化完成后,这个值才会根据设备得到具体的值。初始化ArkUI可以使用windowStage.loadContent接口,在onWindowStageCreate的windowStage.loadContent的回调中使用px2vp即可。
@ohos.app.ability.UIAbility接口文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-app-ability-uiability-0000001774120870#ZH-CN_TOPIC_0000001774120870__uiabilityonwindowstagecreate
windowStage.loadContent接口文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-window-0000001820880785#ZH-CN_TOPIC_0000001820880785__loadcontent9-2