场景一:
aboutToAppear() { this.timer = setInterval(() => { this.progress = Math.min(1, this.progress + 0.05); if (this.progress >= 1) { clearInterval(this.timer); } }, 150); }
Stack({ alignContent: Alignment.Start }) { Image(this.grayImage) .width('100%') .height('100%') .objectFit(ImageFit.Contain) Image(this.colorImage) .width('100%') .height('100%') .objectFit(ImageFit.Contain) .clip(true) .clipShape(new Rect({ width: `${this.progress * 100}%`, height: '100%' })); } .width(300) .height(300)
完整示例参考如下:
@Entry @Component struct ImageProgress { @State progress: number = 0.0; private grayImage: Resource = $r('app.media.start'); // 对应灰色图片 private colorImage: Resource = $r('app.media.final'); // 对应彩色图片 private timer: number = 0; aboutToAppear() { this.timer = setInterval(() => { this.progress = Math.min(1, this.progress + 0.05); if (this.progress >= 1) { clearInterval(this.timer); } }, 150); } aboutToDisappear() { clearInterval(this.timer); } build() { Column() { Stack({ alignContent: Alignment.Start }) { Image(this.grayImage) .width('100%') .height('100%') .objectFit(ImageFit.Contain) Image(this.colorImage) .width('100%') .height('100%') .objectFit(ImageFit.Contain) .clip(true) .clipShape(new Rect({ width: `${this.progress * 100}%`, height: '100%' })); } .width(300) .height(300) StackSample() } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } } @Component export struct StackSample { build() { Column() { Stack() { Image($r('app.media.feature_mine_dibu')).width(100); Image($r('app.media.feature_mine_jindutiao')).width(70); } .alignContent(Alignment.Start) .width('100%') .margin({ top: 50, left: 50 }) .height(5) } .justifyContent(FlexAlign.Center) } }
场景二:
可以通过采用Stack堆叠两张图片的方式,可以设置第一张图片的宽度为指定值,第二张图片通过当前值直接计算出来宽度,即可实现双图片堆叠彩色进度条功能。
@Component export struct StackSample { build() { Column() { Stack() { Image($r('app.media.feature_mine_dibu')).width(100); Image($r('app.media.feature_mine_jindutiao')).width(70); } .alignContent(Alignment.Start) .width('100%') .margin({ top: 50, left: 50 }) .height(5) } .justifyContent(FlexAlign.Center) } }