加入下方官方优快云班级,得鸿蒙礼盒
本期活动时间:2025年8月1日-12月31日
如有问题欢迎私聊我呀
问题现象
如何实现图片进度条功能?未加载时图片进度条是灰色,加载过程中图片进度条由灰色变成彩色,加载完成后图片进度条完全变成彩色。
背景知识
解决方案
- aboutToAppear生命周期中启动定时器,每150ms触发一次,通过增加状态变量progress从0.0到1.0控制图片变化进度。
aboutToAppear() { this.timer = setInterval(() => { this.progress = Math.min(1, this.progress + 0.1) if (this.progress >= 1) { clearInterval(this.timer) } }, 150) } - 使用Stack叠加两张内容相同但颜色不同的图片比如灰色和彩色,彩色图片始终完整显示在底层,灰色图片通过clipShape进行裁剪,裁剪宽度随progress变化。
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)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}

被折叠的 条评论
为什么被折叠?



