HarmonyOS 关于动态设置组件宽度的问题

在设置组件宽度时,需要进行动态设置,使用:

windowClass.getWindowProperties().windowRect.width
  • 1.

获取到的屏幕宽度单位是什么?

let windowWidth:number = windowClass.getWindowProperties().windowRect.width
  • 1.

为何 Row().width(windowWidth) 效果与 Row().width(’100%‘)不一致,是否需要进行单位转换?

HarmonyOS
2024-10-21 10:08:54
1152浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

windowClass.getWindowProperties().windowRect.width获取到的屏幕宽度单位是px,需要把进行单位转换,px2vp(windowWidth) 下面是相关demo:

import window from '@ohos.window';  
import { BusinessError } from '@ohos.base';  
  
@Entry  
@Component  
struct Width {  
  @State message: string = 'Hello World';  
  @State number:number=0;  
  getWidth(){  
    let windowClass: window.Window | undefined = undefined;  
    try {  
      window.getLastWindow(getContext(), (err: BusinessError, data) => {  
        const errCode: number = err.code;  
        if (errCode) {  
          console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));  
        }  
        windowClass = data;  
        let windowWidth:number=windowClass.getWindowProperties().windowRect.width  
  
        this.number= px2vp(windowWidth)  
        console.log(this.number+" oooooo")  
        console.log(JSON.stringify(windowWidth))  
        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));  
      });  
    } catch (exception) {  
      console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));  
    }  
  }  
  
  aboutToAppear(): void {  
    this.getWidth()  
  }  
  
  build() {  
    Row() {  
      Column() {  
        Text(this.message)  
          .fontSize(50)  
          .fontWeight(FontWeight.Bold)  
      }  
      .width('100%')  
    }  
    .height('100%')  
    .width(this.number)  
  }  
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
分享
微博
QQ
微信
回复
2024-10-21 16:58:45


相关问题
关于动态创建组件销毁问题
852浏览 • 1回复 待解决
HarmonyOS 关于canvas中 动态设置lineto
584浏览 • 1回复 待解决
HarmonyOS 组件能否设置最小宽度
639浏览 • 1回复 待解决
HarmonyOS Flex组件宽度问题
1019浏览 • 1回复 待解决
HarmonyOS Tabs组件宽度问题
615浏览 • 1回复 待解决
HarmonyOS Tabs组件tabBar宽度问题
1379浏览 • 1回复 待解决
HarmonyOS关于AXIOS动态传参数问题
1424浏览 • 1回复 待解决
设置组件宽度不超出父组件
1316浏览 • 1回复 待解决
HarmonyOS 子控件设置宽度100%问题
975浏览 • 1回复 待解决
HarmonyOS 关于alertDialog样式设置问题
614浏览 • 1回复 待解决
HarmonyOS 关于代理提醒设置问题
1386浏览 • 1回复 待解决
关于DES加密设置问题
859浏览 • 1回复 待解决
如何设置组件最大最小宽度高度值
3993浏览 • 1回复 待解决
HarmonyOS 关于Navigation组件问题
1453浏览 • 1回复 待解决
HarmonyOS 关于video组件问题
860浏览 • 1回复 待解决
怎么设置元素最大宽度最小宽度
898浏览 • 1回复 待解决
如何动态设置组件属性
1429浏览 • 1回复 待解决
如何设置组件随子组件宽度变化
3030浏览 • 1回复 待解决