层叠布局(StackLayout)用于在屏幕上预留一块区域来显示组件中的元素,提供元素可以重叠的布局。层叠布局通过Stack容器组件实现位置的固定定位与层叠,容器中的子元素依次入栈,后一个子元素覆盖前一个子元素,子元素可以叠加,也可以设置位置。
@Entry @Component struct ImagePage { @State isFullScreen: boolean = false; build() { Column() { Stack() { if (this.isFullScreen) { Column() { Image($r('app.media.startIcon')) // 大图 .width(200) .height(200) } .height('100%') .width('100%') .alignItems(HorizontalAlign.Center) .justifyContent(FlexAlign.Center) .backgroundColor(this.isFullScreen ? '#ffb5b5b5' : '') // 蒙层的背景色 } Column() { Image($r('app.media.startIcon')) // 小图 .width(40) .height(40) .onClick(() => { this.isFullScreen = true; }) } .onClick(() => { this.isFullScreen = false; }) .height('100%') .width('100%') } } .height('100%') .width('100%') } }
通过添加显隐变量,预览时不展示背景模块。
@Entry @Component struct FullScreenImagePage { @State isFullScreen: boolean = false; build() { Column() { Stack() { if (this.isFullScreen) { Column() { Image($r('app.media.startIcon')) .width(200) .height(200) } .height('100%') .width('100%') .alignItems(HorizontalAlign.Center) .justifyContent(FlexAlign.Center) .backgroundColor(this.isFullScreen ? '#FF808080' : '') // 使用Stack布局添加一个蒙层背景。 } Column() { // 通过添加显隐变量,预览时不展示背景模块 if (!this.isFullScreen) { Image($r('app.media.startIcon')) .width(40) .height(40) .onClick(() => { this.isFullScreen = true; }) } } .onClick(() => { this.isFullScreen = false; }) .height('100%') .width('100%') } } .height('100%') .width('100%') } }