中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
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 }) } }
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) } }
效果展示 参考引用自官方文档。
微信扫码分享