RelativeContainer如何让多个view居中

RelativeContainer如何让多个view居屏幕正中间。

HarmonyOS
2024-05-26 11:05:22
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
NGKSWCIDT

使用的核心API

  • RelativeContainer
  • onAreaChange

核心代码解释

通过计算得到Text的宽高,然后定位到中间,代码如下:

@Entry 
@Component 
struct Index1 { 
  
  @State textWidth:number=0 
  @State textHeight:number=0 
  build() { 
    Row() { 
      RelativeContainer() { 
        Image($r('app.media.startIcon')) 
          .width(50).height(50) 
          .alignRules({ 
            top: {anchor: "__container__", align: VerticalAlign.Center}, 
            left: {anchor: "__container__", align: HorizontalAlign.Center} 
          }) 
          .id("row1") 
          .offset({x:-25,y:-(25+this.textHeight/2)}) 
        Row() { 
          Text('我是第一个组件') 
        }.onAreaChange((oldArea: Area, newArea: Area)=>{ 
          console.info('cbl'+newArea.height) 
          if (typeof newArea.width == 'number' && typeof newArea.height == 'number') { 
            this.textWidth =newArea.width 
            this.textHeight=newArea.height 
          } 
        }) 
        .alignRules({ 
          top: {anchor: "row1", align: VerticalAlign.Bottom}, 
          left: {anchor: "row1", align: HorizontalAlign.Start} 
        }) 
        .id("row2") 
        .offset({x:-this.textWidth/2,y:-(25+this.textHeight/2)}) 
      } 
      .border({width:2, color: "#6699FF"}) 
  
    } 
    .height('100%') 
    .width('100%') 
  } 
}

适配版本信息

SDK:4.1.0.52

IDE:DevEco Studio 4.1.1.400

分享
微博
QQ
微信
回复
2024-05-27 10:47:36
相关问题
如何固定应用窗口大小并居中展示
704浏览 • 1回复 待解决
相对布局(RelativeContainer
354浏览 • 1回复 待解决
mysql 如何匹配多个 like 条件?
2612浏览 • 1回复 待解决
mybatis 多个参数时,如何用in?
931浏览 • 1回复 待解决
如何申请多个长时任务
616浏览 • 1回复 待解决
多个UIAbility是多个进程吗
661浏览 • 1回复 待解决
多个UIAbility是多个进程吗?
731浏览 • 1回复 待解决
多个pageAbility之间如何共享变量
542浏览 • 1回复 待解决
如何应用后台持续运行
15479浏览 • 2回复 待解决
关于picker-view的问题
5680浏览 • 1回复 待解决
Input组件是否支持设置文本居中对齐
556浏览 • 1回复 待解决
如何最大化按钮不可用
677浏览 • 1回复 待解决
多个Cookie如何进行批量设置
688浏览 • 1回复 待解决
ArkTS如何开启多个ArkTS 运行环境
509浏览 • 1回复 待解决
如何能够 DevEco studio连接Internet
6191浏览 • 4回复 待解决