文档管理中心
|

ArkUI (方舟UI框架)

UI

HarmonyOS 5

HarmonyOS 如何实现图片进度条彩色显示? (API12+)

HarmonyOS 如何实现图片进度条彩色显示? (API12+)

点赞
收藏
回复
1
分享
举报
浏览17 发布于2026-04-02 11:25未知归属地
全部评论
最多点赞
最新发布
最早发布

1.aboutToAppear生命周期中启动定时器,每500ms触发一次,通过增加状态变量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)
    }
  }, 200)

2.使用Stack叠加两张内容相同但颜色不同的图片比如灰色和彩色,彩色图片始终完整显示在底层,灰色图片通过clipShape进行裁剪,裁剪宽度随progress变化:

Stack({ alignContent: Alignment.Start }) {
  Image(this.colorImage)
    .width('100%')
    .height('100%')
    .objectFit(ImageFit.Contain)
  Image(this.grayImage)
    .width('100%')
    .height('100%')
    .objectFit(ImageFit.Contain)
    .clip(true)
    .clipShape(new Rect({
      width: `${this.progress * 100}%`,
      height: '100%'
    }))
    .transform({ translateX: `${(1 - this.progress) * 300}px` })
}
.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.1)
      if (this.progress >= 1) {
        clearInterval(this.timer)
      }
    }, 200)
  }

aboutToDisappear() {
  clearInterval(this.timer)
}

build() {
  Column() {
    Stack({ alignContent: Alignment.Start }) {
      Image(this.colorImage)
        .width('100%')
        .height('100%')
        .objectFit(ImageFit.Contain)

      Image(this.grayImage)
        .width('100%')
        .height('100%')
        .objectFit(ImageFit.Contain)
        .clip(true)
        .clipShape(new Rect({
          width: `${this.progress * 100}%`,
          height: '100%'
        }))
        .transform({ translateX: `${(1 - this.progress) * 300}px` })
    }
    .width(300)
    .height(300)
  }
  .width('100%')
  .height('100%')
  .justifyContent(FlexAlign.Center)
}
}
展开全部
1楼回复于2026-04-02 11:25 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。