HarmonyOS NEXT 案例实战之 RoundProgress 圆形进度条组件

应用使用场景

圆形进度条(RoundProgress)是一种视觉上吸引人的进度显示方式,常用于以下场景:

  • 健康应用中步数或卡路里目标的完成情况。
  • 音乐或视频应用中播放进度的展示。
  • 仪表盘风格应用中的任务或过程完成百分比。

原理解释

圆形进度条通过围绕一个中心点绘制弧线来表示进度。其工作原理基于设置最大值和当前值,然后计算出对应角度并绘制到界面上。

算法原理流程图

+---------------------------+
| 初始化 RoundProgress 组件 |
+-------------+-------------+
              |
              v
+---------------------------+
| 设置进度条最大值与当前值  |
+-------------+-------------+
              |
              v
+---------------------------+
| 计算进度对应的圆弧角度   |
+-------------+-------------+
              |
              v
+---------------------------+
| 绘制圆弧到界面           |
+---------------------------+

算法原理解释

  1. 初始化 RoundProgress 组件:设置初始样式和参数,包括半径、颜色等。
  2. 设置进度条最大值与当前值:定义总量(最大值)和已完成量(当前值)。
  3. 计算进度对应的圆弧角度:根据当前值占最大值的比例计算圆弧的角度。
  4. 绘制圆弧到界面:在界面上绘制表示进度的圆弧。

ArkTS + ArkUI 代码示例实现

import { Canvas, Color } from '@ohos/ui';

// 创建圆形进度条组件
function createRoundProgress(radius: number, maxValue: number) {
    let currentValue = 0;

    const canvas = new Canvas();
    canvas.width = 2 * radius;
    canvas.height = 2 * radius;

    // 绘制函数
    function draw() {
        const context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);

        // 背景圆圈
        context.beginPath();
        context.arc(radius, radius, radius - 5, 0, 2 * Math.PI);
        context.strokeStyle = '#e0e0e0';
        context.lineWidth = 10;
        context.stroke();

        // 前景圆弧
        context.beginPath();
        const endAngle = (currentValue / maxValue) * 2 * Math.PI;
        context.arc(radius, radius, radius - 5, -Math.PI / 2, endAngle - Math.PI / 2);
        context.strokeStyle = '#4caf50';
        context.lineWidth = 10;
        context.stroke();

        // 中心文本
        context.font = '20px Arial';
        context.fillStyle = '#333';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.fillText(`${Math.round((currentValue / maxValue) * 100)}%`, radius, radius);
    }

    // 更新进度的函数
    function updateProgress(value: number) {
        currentValue = value;
        draw();
    }

    return { canvas, updateProgress };
}

// 使用圆形进度条组件
const roundProgress = createRoundProgress(100, 100);
document.body.appendChild(roundProgress.canvas);

// 模拟进度更新
let simulatedProgress = 0;
const intervalId = setInterval(() => {
    if (simulatedProgress <= 100) {
        roundProgress.updateProgress(simulatedProgress);
        simulatedProgress += 5;  // 每次增加5%
    } else {
        clearInterval(intervalId);  // 停止更新
        console.log('Progress complete!');
    }
}, 1000);  // 每秒更新一次

测试代码与部署场景

  1. 测试代码:验证进度条在不同进度值下的准确性,并确保在多种设备分辨率下正确显示。
  2. 部署场景:在智能手表、手机、平板等多种设备上测试,以了解适应性和用户体验。

材料链接

总结

圆形进度条以其直观的视觉表现形式,在提升用户体验方面具有独特优势。在开发中,应注意保持动画流畅,确保在各种设备上的优化显示。

未来展望

随着图形处理能力的增强,未来的圆形进度条可能会支持更丰富的视觉效果,如渐变色彩、动态纹理等。此外,结合 AR/VR 技术和触觉反馈装置,未来的进度条将提供更加沉浸式的用户体验。