[文章]HarmonyOS/OpenHarmony应用开发ArkTS自适应线性布局定位能力实现

阅读量0
0
1

1.相对定位,使用组件的offset属性可以实现相对定位,设置元素相对于自身的偏移量。设置该属性,不影响父容器布局,仅在绘制时进行位置调整。使用线性布局和offset可以实现大部分布局的开发。
代码实现

@Entry
@Component
struct OffsetExample {
  @Styles eleStyle() {
    .size({ width: 120, height: '50' })
    .backgroundColor(0xbbb2cb)
    .border({ width: 1 })
  }

  build() {
    Column({ space: 20 }) {
      Row() {
        Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
        Text('2  offset(15, 30)')
          .eleStyle()
          .fontSize(16)
          .align(Alignment.Start)
          .offset({ x: 15, y: 30 })
        Text('3').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
        Text('4 offset(-10%, 20%)')
          .eleStyle()
          .fontSize(16)
          .offset({ x: '-5%', y: '20%' })
      }.width('90%').height(150).border({ width: 1, style: BorderStyle.Dashed })
    }
    .width('100%')
    .margin({ top: 25 })
  }
} 

HarmonyOS/OpenHarmony应用开发ArkTS自适应线性布局定位能力实现-开源基础软件社区HarmonyOS/OpenHarmony应用开发ArkTS自适应线性布局定位能力实现-开源基础软件社区
2.绝对定位
线性布局中可以使用组件的positon属性实现绝对布局(AbsoluteLayout),设置元素左上角相对于父容器左上角偏移位置。对于不同尺寸的设备,使用绝对定位的适应性会比较差,在屏幕的适配上有缺陷。
代码实现

@Entry
@Component
struct PositionExample {
  @Styles eleStyle(){
    .backgroundColor(0xbbb2cb)
    .border({ width: 1 })
    .size({ width: 120, height: 50 })
  }

  build() {
    Column({ space: 20 }) {
      // 设置子组件左上角相对于父组件左上角的偏移位置
      Row() {
        Text('position(30, 10)')
          .eleStyle()
          .fontSize(16)
          .position({ x: 10, y: 10 })

        Text('position(50%, 70%)')
          .eleStyle()
          .fontSize(16)
          .position({ x: '50%', y: '70%' })

        Text('position(10%, 90%)')
          .eleStyle()
          .fontSize(16)
          .position({ x: '10%', y: '80%' })
      }.width('90%').height('100%').border({ width: 1, style: BorderStyle.Dashed })
    }
    .width('90%').margin(25)
  }
}

效果展示
HarmonyOS/OpenHarmony应用开发ArkTS自适应线性布局定位能力实现-开源基础软件社区HarmonyOS/OpenHarmony应用开发ArkTS自适应线性布局定位能力实现-开源基础软件社区
参考引用自官方文档。

回帖

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容图片侵权或者其他问题,请联系本站作侵删。 侵权投诉
链接复制成功,分享给好友