- 在水平方向上,可以设置left、middle、right的锚点。
- 在竖直方向上,可以设置top、center、bottom的锚点。
- 必须为RelativeContainer及其子元素设置ID,用于指定锚点信息。RelativeContainer的ID默认为
__container__
1、RelativeContainer父组件为锚点,__container__代表父容器的id
RelativeContainer() { Row(){ Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) } // 添加其他属性 .alignRules({ top: { anchor: 'container', align: VerticalAlign.Top }, left: { anchor: 'container', align: HorizontalAlign.Start } }) .id("row1") Row(){ Text('2').width('33%').height(50).backgroundColor(0xD2B48C) } .alignRules({ top: { anchor: 'container', align: VerticalAlign.Top }, right: { anchor: 'container', align: HorizontalAlign.End } }) .id("row2") } .width(300).height(300) .margin({ left: 20 }) .border({ width: 2, color: '#6699FF' })
2、以子元素为锚点
RelativeContainer() { Row(){ Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) } // 添加其他属性 .alignRules({ top: { anchor: 'container', align: VerticalAlign.Top }, left: { anchor: 'container', align: HorizontalAlign.Start } }) .id("row1") Row(){ Text('2').width('33%').height(50).backgroundColor(0xD2B48C) } .alignRules({ top: { anchor: 'row1', align: VerticalAlign.Bottom }, right: { anchor: 'row1', align: HorizontalAlign.End } }) .id("row2") } .width(300).height(300) .margin({ left: 20 }) .border({ width: 2, color: '#6699FF' })
2.2 设置相对于锚点的对齐位置
1、在水平方向上,对齐位置可以设置为HorizontalAlign.Start、HorizontalAlign.Center、HorizontalAlign.End
2、在竖直方向上,对齐位置可以设置为VerticalAlign.Top、VerticalAlign.Center、VerticalAlign.Bottom
3.案例
@Entry @Component struct Index { build() { Row() { RelativeContainer() { Row() .width(100) .height(100) .backgroundColor('#FF3333') .alignRules({ top: { anchor: 'container', align: VerticalAlign.Top }, //以父容器为锚点,竖直方向顶头对齐 middle: { anchor: 'container', align: HorizontalAlign.Center } //以父容器为锚点,水平方向居中对齐 }) .id('row1') //设置锚点为row1
Row() { Image($r('app.media.icon')) } .height(100).width(100) .alignRules({ top: { anchor: 'row1', align: VerticalAlign.Bottom }, //以row1组件为锚点,竖直方向低端对齐 left: { anchor: 'row1', align: HorizontalAlign.Start } //以row1组件为锚点,水平方向开头对齐 }) .id('row2') //设置锚点为row2
Row() .width(100) .height(100) .backgroundColor('#FFCC00') .alignRules({ top: { anchor: 'row2', align: VerticalAlign.Top } }) .id('row3') //设置锚点为row3
Row() .width(100) .height(100) .backgroundColor('#FF9966') .alignRules({ top: { anchor: 'row2', align: VerticalAlign.Top }, left: { anchor: 'row2', align: HorizontalAlign.End }, }) .id('row4') //设置锚点为row4
Row() .width(100) .height(100) .backgroundColor('#FF66FF') .alignRules({ top: { anchor: 'row2', align: VerticalAlign.Bottom }, middle: { anchor: 'row2', align: HorizontalAlign.Center } }) .id('row5') //设置锚点为row5 } .width(300).height(300) .border({ width: 2, color: '#6699FF' }) } .height('100%').margin({ left: 30 }) } }
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!