HarmonyOS 绝对定位如何让组件在屏幕正中间

采用绝对定位一个按钮如何才能保证这个按钮的绝对居中在屏幕的正中间。

HarmonyOS
2024-09-26 13:20:46
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

示例如下:

import window from '@ohos.window';  
import { BreakpointSystem, Num } from './Util';  
import display from '@ohos.display';  
  
@Entry  
@Component  
struct Index {  
  @State message: string = 'Hello World';  
  @State buttonWidth: number = 100;  
  @State buttonHeight: number = 50;  
  @State x: number = 0;  
  @State y: number = 0;  
  
  aboutToAppear() {  
    display.getAllDisplays((err, data) => {  
      let screenWidth: number = data[0].width  
      let screenHeight: number = data[0].height  
      // 将长度的单位由px换算为vp  
      let windowWidthVp = screenWidth / display.getDefaultDisplaySync().densityPixels  
      let windowHeightVp = screenHeight / display.getDefaultDisplaySync().densityPixels  
      this.x = (windowWidthVp-this.buttonWidth)/2  
      this.y = (windowHeightVp-this.buttonHeight)/2 - this.buttonHeight/2  
    })  
  }  
  build() {  
  
    Column() {  
      Button('点击')  
        .fontColor('#ffef1515')  
        .width(this.buttonWidth+'vp')  
        .height(this.buttonHeight+'vp')  
        .position({ x: this.x, y:  this.y})  
        .backgroundColor('#fff3d579')  
    }.width('100%')  
    .height('100%')  
  }  
}

也可以参考 属性 .justifyContent(FlexAlign.Center) 属性 .alignItems(HorizontalAlign.Center)

@Entry  
@Component  
struct Index {  
  @State message: string = 'Hello World';  
  @State buttonWidth: number = 100;  
  @State buttonHeight: number = 50;  
  build() {  
    Column() {  
      Button('点击')  
        .fontColor('#ffef1515')  
        .width(this.buttonWidth+'vp')  
        .height(this.buttonHeight+'vp')  
        .backgroundColor('#fff3d579')  
    }  
    .justifyContent(FlexAlign.Center)  
    .width('100%')  
    .height('100%')  
  }  
  
}
分享
微博
QQ
微信
回复
2024-09-26 17:32:34
相关问题
如何将容器定位屏幕的最底部
2356浏览 • 1回复 待解决
HarmonyOS Textinput如何实现中间插入
361浏览 • 1回复 待解决
HarmonyOS 绝对布局位置不对
334浏览 • 0回复 待解决