HarmonyOS ArkTS Canvas 画环形进度条 animateTo + @Watch 驱动重绘 120 行实现

1,261 阅读6分钟

鸿蒙 ArkUI 的 Progress 组件支持圆形模式,但样式有限——不支持渐变色、不支持虚线内环、不支持圆帽 lineCap。做某个"精力/习惯管理"类 app 想要一个"赛博朋克" 风格的环形进度(紫→青渐变 + 虚线内圈 + 圆帽端点),自己用 Canvas 画了一版。120 行,animateTo 驱动动画。记录一下,顺便分享给有需要的朋友。

一、朴素 Progress 组件够不够

鸿蒙原生:

Progress({ value: 60, total: 100, type: ProgressType.Ring })
  .width(160)
  .height(160)
  .color('#4CAF50')

支持:

  • 四种 type:Linear / Ring / Scale / Capsule / Eclipse
  • 单色填充 color
  • percentage style 自带数字

不支持:

  • 多色渐变(想要 "紫→青" 渐变做不出)
  • 内环装饰(虚线圈、刻度)
  • 圆帽端点(lineCap 'round')
  • 自定义动画曲线

什么时候自己画:想要上面几项里任何一样 → 走 Canvas。

二、EnergyRingChart 的核心代码

// EnergyRingChart.ets
@Component
export struct EnergyRingChart {
  @Prop currentTokens: number = 1000
  @Prop maxTokens: number = 1000
  @State @Watch('onPctChange') animatedPct: number = 0

  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private readonly chartSize: number = 160
  private timerId: number = -1
  private canvasReady: boolean = false

  aboutToAppear(): void {
    this.timerId = setTimeout(() => {
      animateTo({ duration: 800, curve: Curve.EaseOut }, () => {
        this.animatedPct = Math.max(0, (this.currentTokens / this.maxTokens) * 100)
      })
    }, 200)
  }

  aboutToDisappear(): void {
    if (this.timerId !== -1) {
      clearTimeout(this.timerId)
    }
  }

  onPctChange(): void {
    if (this.canvasReady) {
      this.drawRing()
    }
  }

  private drawRing(): void {
    const w = this.chartSize
    const h = this.chartSize
    const cx = w / 2
    const cy = h / 2
    const r = 68           // 外圈半径
    const lw = 10          // 线宽

    this.ctx.clearRect(0, 0, w, h)

    // 1. 外圈底色(灰色底环)
    this.ctx.beginPath()
    this.ctx.arc(cx, cy, r, 0, Math.PI * 2)
    this.ctx.lineWidth = lw
    this.ctx.strokeStyle = '#1a94a3b8'
    this.ctx.stroke()

    // 2. 内圈虚线装饰
    this.ctx.beginPath()
    this.ctx.arc(cx, cy, 54, 0, Math.PI * 2)
    this.ctx.lineWidth = 1
    this.ctx.strokeStyle = '#1a94a3b8'
    this.ctx.setLineDash([3, 4])            // 虚线:3 实 4 虚
    this.ctx.stroke()
    this.ctx.setLineDash([])                 // 复位

    // 3. 真正的进度弧(紫→青渐变)
    if (this.animatedPct > 0) {
      const startAngle = -Math.PI / 2      // 从正上方开始
      const endAngle = startAngle + (Math.PI * 2 * this.animatedPct / 100)

      // 线性渐变
      const gradient = this.ctx.createLinearGradient(0, 0, w, h)
      gradient.addColorStop(0, '#8b5cf6')  // 紫
      gradient.addColorStop(1, '#06b6d4')  // 青

      this.ctx.beginPath()
      this.ctx.arc(cx, cy, r, startAngle, endAngle)
      this.ctx.lineWidth = lw
      this.ctx.strokeStyle = gradient
      this.ctx.lineCap = 'round'           // 圆帽端点
      this.ctx.stroke()
    }
  }

  build() {
    Canvas(this.ctx)
      .width(this.chartSize)
      .height(this.chartSize)
      .onReady(() => {
        this.canvasReady = true
        this.drawRing()
      })
  }
}

120 行左右,核心 drawRing 50 行。

三、三层叠加:底环 + 虚线内环 + 进度弧

第 1 层:灰色底环

this.ctx.beginPath()
this.ctx.arc(cx, cy, r, 0, Math.PI * 2)
this.ctx.lineWidth = 10
this.ctx.strokeStyle = '#1a94a3b8'   // 带 alpha 的淡灰
this.ctx.stroke()

作用:告诉用户 "满量程" 在哪里。进度弧是实色,底环是淡色,对比明确。

第 2 层:虚线内环

this.ctx.setLineDash([3, 4])          // 虚线模式
this.ctx.beginPath()
this.ctx.arc(cx, cy, 54, 0, Math.PI * 2)   // 比外环小的内圈
this.ctx.lineWidth = 1
this.ctx.strokeStyle = '#1a94a3b8'
this.ctx.stroke()
this.ctx.setLineDash([])              // 复位

作用:纯装饰。让环的视觉更丰富,像"仪表盘"的刻度感。不加也 OK,加了更美。

setLineDash([3, 4]):3 像素实线 + 4 像素空隙 → 虚线。可以调成 [5, 2] 短虚、[10, 10] 长虚。

用完要 setLineDash([]) 复位,不然后面画的也是虚线。

第 3 层:真正的进度弧

const startAngle = -Math.PI / 2       // 正上方 12 点钟
const endAngle = startAngle + (Math.PI * 2 * pct / 100)

startAngle = -π/2:Canvas 的 arc 默认 0 弧度在正右方 3 点钟。减 π/2 让起点在12 点钟(更符合"进度条"的直觉)。

lineCap = 'round':进度弧两端是圆帽,不是直角。看起来更友好。

渐变 createLinearGradient(0, 0, w, h):从左上角到右下角的渐变。进度弧沿弧线采样这个渐变色。

四、animateTo + @Watch 的动画

第一次挂载时的入场动画:

aboutToAppear(): void {
  this.timerId = setTimeout(() => {
    animateTo({ duration: 800, curve: Curve.EaseOut }, () => {
      this.animatedPct = Math.max(0, (this.currentTokens / this.maxTokens) * 100)
    })
  }, 200)
}

流程:

  1. 组件挂载时 animatedPct = 0
  2. setTimeout 200ms 后开始动画
  3. animateTo(800ms, EaseOut) 把 animatedPct 从 0 → 目标值
  4. ArkUI 自动插值,每帧 animatedPct 变一点
  5. @Watch 监听 animatedPct 变化 → 调 drawRing 重画

用户看到:环从 0 展开到当前值,像能量充满的动画。EaseOut 让"初快末慢",仪式感强。

为什么 200ms 的 setTimeout:

  • 组件刚挂载 Canvas 可能还没 ready
  • onReady 回调要先触发 this.canvasReady = true
  • 200ms 保证 Canvas ready 之后再启动动画

@Watch 的触发:

@State @Watch('onPctChange') animatedPct: number = 0

onPctChange(): void {
  if (this.canvasReady) {
    this.drawRing()
  }
}

每次 animatedPct 变化 → 调 onPctChange → 调 drawRing。因为 animateTo 的插值是 60fps,一秒 60 次重画。

60fps Canvas 重画够吗:环是 50 行代码的画法,一次重画 ~1-2ms。60 fps 下 CPU 占用 < 5%,流畅。

五、Prop 变化重新动画

用户的 tokens 发生变化(吃任务消耗一些、休息回复一些),currentTokens prop 变。想重新动画 →

@Prop @Watch('onTokensChange') currentTokens: number = 1000

onTokensChange(): void {
  animateTo({ duration: 500, curve: Curve.EaseInOut }, () => {
    this.animatedPct = Math.max(0, (this.currentTokens / this.maxTokens) * 100)
  })
}

比入场动画短(500ms vs 800ms)。入场是"仪式",更新是"反应"。更新动画不应太长,否则看起来迟钝。

EaseInOut vs EaseOut:

  • EaseOut:初快末慢,仪式感
  • EaseInOut:两端都慢,中间快,自然感
  • 入场用 EaseOut,更新用 EaseInOut

六、aboutToDisappear 清理

aboutToDisappear(): void {
  if (this.timerId !== -1) {
    clearTimeout(this.timerId)
  }
}

清理 setTimeout:组件销毁时如果 setTimeout 还没触发(200ms 内切了页面),animateTo 会在 null 组件上尝试执行,有可能报错。

animateTo 本身不用清:ArkUI 的 animation 挂在 @State 字段上,组件销毁时自动停。

七、Canvas vs ArkUI 的方案对比

同样画环形进度:

方案优点缺点
原生 Progress Ring简单(1 行)不支持渐变 / 虚线 / 圆帽
Canvas(本文)完全可控样式120 行代码 + 要处理动画驱动
组合 Circle + Stack原生组件,无 Canvas做不出渐变弧线

什么时候用 Canvas:

  • 需要渐变色
  • 需要虚线 / 刻度装饰
  • 需要非 100% 整圆的进度(弧度 270°、180° 这种)
  • 需要叠加文字 / 图标 在中心

本篇场景三者都需要 → Canvas 是正解。

八、.animation vs animateTo 的差异

.animation(声明式):

Circle({ width: this.scale * 100 })
  .animation({ duration: 300, curve: Curve.EaseInOut })

挂在组件上,组件的所有属性变化都走这个 animation 定义的曲线。

animateTo(指令式):

animateTo({ duration: 800, curve: Curve.EaseOut }, () => {
  this.animatedPct = 100
})

包一个 state 变更,这次变更的插值走指定曲线。

对 Canvas 场景,必须用 animateTo。因为 Canvas 不是"声明式属性",是手工 drawRing。.animation 挂在 Canvas 组件上不触发 drawRing,只有 animateTo 包的 state 变更才会通过 @Watch 触发重画。

踩坑清单

  • RenderingContextSettings(true) 开抗锯齿
  • 三层画法:底环 + 虚线内环 + 进度弧
  • setLineDash([3, 4]) 画虚线,用完 setLineDash([]) 复位
  • 进度弧起点 -Math.PI / 2 从正上方开始
  • lineCap = 'round' 圆帽端点,视觉更友好
  • createLinearGradient 渐变色作为 strokeStyle
  • animateTo + @State animatedPct + @Watch onPctChange + drawRing 的驱动链
  • setTimeout 200ms 等 Canvas ready
  • 入场 EaseOut 800ms,更新 EaseInOut 500ms
  • aboutToDisappear 清 setTimeout

尾声

自定义 Canvas 组件是鸿蒙 ArkUI 的"个性化" 方向。原生 Progress 够用但大家都一样,Canvas 版的渐变 + 虚线 + 圆帽让 app 一眼不同。

独立开发者的建议:

  • 第一版 app 用原生组件,功能先跑起来
  • 稳定后把 几个核心 UI(Dashboard、Stats 页首屏)换成 Canvas 自绘,提升品质感
  • Canvas 不是炫技,是在"我不想和别人一样"的点上多投一天

一个意外发现:渐变色环比单色环感觉"先进 50%"。工程上就是多两行 createLinearGradient + addColorStop,视觉上是一个数量级的提升。