层叠布局
前言
主要是记录我对openharmony中层叠布局的学习,有错误的地方,还望各位指教
Stack组件(可以包含子组件)
作为容器组件,容器内可以包含各种子元素。其中子元素默认进行居中堆叠
@Entry
@Component
struct StackPage {
@State num: number = 10;
build() {
Column(){
Stack(){
Column(){}.width('80%')
.height('70%')
.backgroundColor(Color.Brown)
Text(this.num.toString())
.fontColor(Color.Black)
.backgroundColor(Color.Orange)
.height('40%')
.width('70%')
.fontWeight(FontWeight.Bold)
Button('button')
.type(ButtonType.Circle)
.onClick((event: ClickEvent) => {
if(this.num>0){
this.num-=2
}else{
this.num+=8
}
})
.backgroundColor(Color.Green)
.width('30%')
.height('20%')
}.width('100%')
.height('100%')
}
}
}
对齐方式
接下来的代码是演示Stack组件的九种对齐方式,代码除了Stack括号中的内容不同外,没有其他的区别
@Entry
@Component
struct StackPage {
@State num: number = 10;
build() {
Column(){
Stack({alignContent:Alignment.TopStart}){
Column(){}.width('80%')
.height('70%')
.backgroundColor(Color.Brown)
Text(this.num.toString())
.fontColor(Color.Black)
.backgroundColor(Color.Orange)
.height('40%')
.width('70%')
.fontWeight(FontWeight.Bold)
.align(Alignment.BottomEnd)//设置该容器中的文字的位置
Button('button')
.type(ButtonType.Circle)
.onClick(() => {
if(this.num>0){
this.num-=2
}else{
this.num+=8
}
})
.backgroundColor(Color.Green)
.width('30%')
.height('20%')
}.width('100%')
.height('100%')
}
}
}
TopStart
Stack({alignContent:Alignment.Top})
Top
Stack({alignContent:Alignment.TopEnd})
TopEnd
Stack({alignContent:Alignment.Start})
Start
Stack({alignContent:Alignment.Center})
Center
Stack({alignContent:Alignment.End})
End
Stack({alignContent:Alignment.BottomStart})
BottomStart
Stack({alignContent:Alignment.Bottom})
Bottom
Stack({alignContent:Alignment.BottomEnd})
BottomEnd
Z序控制
Stack容器中兄弟组件显示层级关系可以通过Z序控制的zIndex属性改变。zIndex值越大,显示层级越高,即zIndex值大的组件会覆盖在zIndex值小的组件上方。
@Entry
@Component
struct StackPage {
@State num: number = 10;
build() {
Column(){
Stack({alignContent:Alignment.Center}){
Text('元素1')
.backgroundColor(Color.Brown)
.width('30%')
.height('30%')
.align(Alignment.BottomEnd)
.zIndex(3)
Text('元素2')
.backgroundColor(Color.Orange)
.width('50%')
.height('50%')
.align(Alignment.BottomEnd)
.zIndex(2)
Text('元素3')
.backgroundColor(Color.Gray)
.width('70%')
.height('70%')
.align(Alignment.BottomEnd)
.zIndex(1)
}.width('100%')
.height('100%')
}
}
}