第12篇:Canvas 画布组件——绘制练习进度条

在这里插入图片描述

一、引言

Canvas 是鸿蒙 ArkUI 提供的 2D 画布组件,支持通过 CanvasRenderingContext2D API 绘制图形。DriverLicenseExam 项目使用 Canvas 绘制了练习进度条,展示了答题进度。本文将深度解析 Canvas 组件的使用。

二、CanvasView 组件实现

2.1 组件结构

// products/entry/src/main/ets/pages/home/HomeView.ets
@ComponentV2
struct CanvasView {
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D();
  @Param didCount: number = 0;     // 已做题数
  @Param totalCount: number = 0;   // 总题数

  build() {
    Canvas(this.context)
      .width(CommonConstants.FULL_WIDTH)
      .height(10)
      .onReady(() => {
        this.drawProgress();
      });
  }
}

2.2 进度条绘制逻辑

@Monitor('didCount')
drawProgress() {
  const width = this.context.width;
  const height = this.context.height;
  
  // 清空画布
  this.context.clearRect(0, 0, width, height);

  // 计算已完成部分宽度
  const doneWidth = width * this.didCount / this.totalCount;

  // 绘制已完成部分(实线)
  this.context.beginPath();
  this.context.strokeStyle = '#64BB5C';     // 绿色
  this.context.lineWidth = 2;
  this.context.setLineDash([5, 0]);         // 实线
  this.context.moveTo(0, 5);
  this.context.lineTo(doneWidth, 5);
  this.context.stroke();

  // 绘制未完成部分(虚线)
  this.context.beginPath();
  this.context.strokeStyle = 'rgba(0, 0, 0, 0.3)';  // 半透明灰色
  this.context.lineWidth = 2;
  this.context.setLineDash([5, 3]);          // 虚线
  this.context.moveTo(doneWidth, 5);
  this.context.lineTo(width, 5);
  this.context.stroke();
}

三、Canvas 绘制 API 详解

3.1 核心 API

// 创建 CanvasRenderingContext2D
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D();

// 清空画布
context.clearRect(x, y, width, height);

// 开始路径
context.beginPath();

// 设置描边颜色
context.strokeStyle = '#64BB5C';

// 设置线宽
context.lineWidth = 2;

// 设置虚线样式
context.setLineDash([segment, gap]);  // [实线长度, 间隔长度]

// 移动画笔
context.moveTo(x, y);

// 绘制直线
context.lineTo(x, y);

// 描边
context.stroke();

3.2 响应式更新

通过 @Monitor 装饰器监听 didCount 变化,自动重绘:

@Monitor('didCount')
drawProgress() {
  // 当 didCount 变化时,自动重绘进度条
  this.context.clearRect(0, 0, width, height);
  // ... 重新绘制
}

四、总结

Canvas 组件为 ArkUI 提供了灵活的 2D 绘图能力。通过 CanvasRenderingContext2D API,可以实现各种自定义图形和动画效果。结合 @Monitor 装饰器,Canvas 可以轻松实现响应式更新。


关键源码文件:

  • products/entry/src/main/ets/pages/home/HomeView.ets — CanvasView 组件
Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐