层叠布局(Stack)
知识点
- Stack 布局 没有 ZIndex 的时候 越往后 权重越高
概述
层叠布局通过 Stack 容器组件实现位置的固定定位与层叠,容器中的子元素依次入栈,后一个子元素覆盖前一个子元素,子元素可以叠加,也可以设置位置。
开发布局
Stack 组件为容器组件,容器内可包含各种子元素。其中子元素默认进行居中堆叠。子元素被约束在 Stack 下,进行自己的样式定义以及排列。
对齐方式
Stack 组件通过 alignContent 参数实现位置的相对移动。支持九种对齐方式。
通过参数 alignContent 设置对齐方式,可选值如下:
ts
// xxx.ets
@Entry
@Component
struct StackExample {
build() {
Stack({ alignContent: Alignment.TopStart }) {
Text('Stack').width('90%').height('100%').backgroundColor('#e1dede').align(Alignment.BottomEnd)
Text('Item 1').width('70%').height('80%').backgroundColor(0xd2cab3).align(Alignment.BottomEnd)
Text('Item 2').width('50%').height('60%').backgroundColor(0xc1cbac).align(Alignment.BottomEnd)
}.width('100%').height(150).margin({ top: 5 })
}
}
Z 序控制
Stack 容器中兄弟组件显示层级关系可以通过 Z 序控制的 zIndex 属性改变。
zIndex 值越大,显示层级越高,即 zIndex 值大的组件会覆盖在 zIndex 值小的组件上方。
在层叠布局中,如果后面子元素尺寸大于前面子元素尺寸,则前面子元素完全隐藏。
ts
Stack({ alignContent: Alignment.BottomStart }) {
Column() {
Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20)
}.width(100).height(100).backgroundColor(0xffd306)
Column() {
Text('Stack子元素2').fontSize(20)
}.width(150).height(150).backgroundColor(Color.Pink)
Column() {
Text('Stack子元素3').fontSize(20)
}.width(200).height(200).backgroundColor(Color.Grey)
}.width(350).height(350).backgroundColor(0xe0e0e0)
- 设定 zIndex 以后则按照 zIndex 的值进行排序,zIndex 值大的组件会覆盖在 zIndex 值小的组件上方。
ts
Stack({ alignContent: Alignment.BottomStart }) {
Column() {
Text('Stack子元素1').fontSize(20)
}.width(100).height(100).backgroundColor(0xffd306).zIndex(2)
Column() {
Text('Stack子元素2').fontSize(20)
}.width(150).height(150).backgroundColor(Color.Pink).zIndex(1)
Column() {
Text('Stack子元素3').fontSize(20)
}.width(200).height(200).backgroundColor(Color.Grey)
}.width(350).height(350).backgroundColor(0xe0e0e0)
右下角定位
ts
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Stack({alignContent:Alignment.BottomEnd}){
Column(){
Row(){
Text(this.message).fontSize(23).fontColor(Color.White)
}
}
.width('100%')
.height('100%')
.backgroundColor(Color.Black)
Text("+")
.fontSize(25)
.width(100)
.height(100)
.borderRadius(50)
.backgroundColor(Color.Red)
.zIndex(2)
.position({
bottom:30,
right:30
})
}
}
}