ArkUI层叠布局(Stack)
1. 层叠布局概述
层叠布局通过Stack
容器组件实现位置的固定定位与层叠,容器中的子元素(子组件)依次入栈,后一个子元素覆盖前一个子元素。
2. 层叠布局的使用
@Entry
@Component
struct StackLayout {
build() {
Stack() {
Column() {}
.width("100%")
.height(300)
.backgroundColor(Color.Red)
Column() {}
.width("80%")
.height(200)
.backgroundColor(Color.Blue)
Column() {}
.width("60%")
.height(100)
.backgroundColor(Color.Pink)
}
}
}
Stack
容器组件的特点:
- 按照子元素的先后顺序层叠,后面的元素覆盖在前面的元素上面。
- 默认的对齐方式是垂直水平居中。
- 不指定宽的情况,
Stack
容器组件的宽等于子元素中最宽的长度。 - 不指定高的情况,
Stack
容器组件的高等于子元素中最高的长度。
2. 层叠布局的对齐方式
Stack
容器组件通过alignContent
参数实现位置的相对移动。
- Alignment.TopStart:顶部开端
- Alignment.Top:顶部居中
- Alignment.TopEnd:顶部尾部
- Alignment.Start:左侧居中
- Alignment.Center:中心点(默认值)
- Alignment.End:右侧居中
- Alignment.BottomStart:底部开端
- Alignment.Bottom:底部居中
- Alignment.BottomEnd:底部尾部
@Entry
@Component
struct StackLayout {
build() {
// 设置对齐方式为顶部开端
Stack({alignContent: Alignment.TopStart}) {
Column() {}
.width("100%")
.height(300)
.backgroundColor(Color.Red)
Column() {}
.width("80%")
.height(200)
.backgroundColor(Color.Blue)
Column() {}
.width("60%")
.height(100)
.backgroundColor(Color.Pink)
}
}
}
@Entry
@Component
struct StackLayout {
build() {
// 设置对齐方式为顶部中间
Stack({alignContent: Alignment.Top}) {
Column() {}
.width("100%")
.height(300)
.backgroundColor(Color.Red)
Column() {}
.width("80%")
.height(200)
.backgroundColor(Color.Blue)
Column() {}
.width("60%")
.height(100)
.backgroundColor(Color.Pink)
}
}
}
@Entry
@Component
struct StackLayout {
build() {
// 设置对齐方式为顶部尾部
Stack({alignContent: Alignment.TopEnd}) {
Column() {}
.width("100%")
.height(300)
.backgroundColor(Color.Red)
Column() {}
.width("80%")
.height(200)
.backgroundColor(Color.Blue)
Column() {}
.width("60%")
.height(100)
.backgroundColor(Color.Pink)
}
}
}
上述演示了 Alignment.TopStart
、Alignment.Top
、Alignment.TopEnd
三种对齐方式,其他的对齐方式大家可以用相同的方式依次测试。
4. Z 序控制
Stack
容器组件中,默认的子元素的层叠是根据元素引用的先后顺序。Stack
容器中子元素显示层级关系可以通过Z序控制的zIndex
属性改变。zIndex
值越大,显示层级越高。
@Entry
@Component
struct StackLayout {
build() {
Stack() {
Column() {}
.width("60%")
.height(100)
.backgroundColor(Color.Pink)
.zIndex(3)
Column() {}
.width("80%")
.height(200)
.backgroundColor(Color.Blue)
.zIndex(2)
Column() {}
.width("100%")
.height(300)
.backgroundColor(Color.Red)
.zIndex(1)
}
}
}