QML进阶-球形进度条(圆形进度条)

先上图,确认一下是否是你需要的图片。

实现思路

1、利用canvas画图工具画出圆形circle1(外围的大圆)
2、画出内部的小圆区域,利用clip函数裁剪。裁剪后,只有圆内的图像才可以显示,圆外的不显示。clip裁剪的功能如果你不懂,可以[看这里](https://www.w3school.com.cn/tags/canvas_clip.asp)
3、裁剪后利用percent绑定填充区域的上边界,进行颜色填充,填充的时候,我们采用矩形填充即可,如下图,因为clip已经限定了只能在圆内显示。
4、设置一个定时器,来自动的更显percent的值。
不添加clip()图像如下:
添加clip()的图像如下:

实现代码

CircleProcBar.qml

import QtQml 2.12
import QtQuick 2.12
import QtQuick.Controls 2.12

Rectangle {
    width: 220
    height: 220

    property int percent: 0
    Canvas {    
        id:canvas
        anchors.fill: parent
        onPaint: {
            var ctx = getContext("2d");

            ctx.clearRect(0, 0, width, height); // 清除一块矩形区域
            ctx.beginPath(); // 开始画图
            ctx.lineWidth =3 // 设置边线粗为3
            ctx.strokeStyle = '#148113'; // 设置颜色
            ctx.arc(width / 2, height / 2, width / 2 - 5, 0, 2*Math.PI);  // arc函数画大圆
            ctx.stroke(); // 设置大圆圈颜色

            ctx.beginPath();
            ctx.arc(width / 2, height / 2, width / 2 - 10, 0, 2*Math.PI);  // 绘制第二个小圆区域
            ctx.clip(); // 进行裁剪
            ctx.save(); // 保存当前状态,压入栈内

            ctx.beginPath();
            ctx.lineTo(0, height -10 - percent * (width - 20) / 100); // 绘制填充矩形左上角[0,height - bottomMargin - 填充高度],圆圈距离矩形框上下左右四个边的距离都是10个像素
            ctx.lineTo(width, height -10 - percent * (height - 20) / 100); // 绘制填充矩形右上角,[width,height - bottomMargin - 填充高度]
            ctx.lineTo(width, height -10); // 绘制填充矩形左下角
            ctx.lineTo(0, height -10) // 绘制填充矩形右下角
            ctx.lineTo(0, height -10 - percent * (width - 20) / 100); // 回到起点,形成一个矩形
            ctx.fillStyle = '#148014'; 
            ctx.fill();  // 对区域进行填充
            ctx.restore(); // 回退栈
        }

    }
    Timer {
        id: runTimer
        running: false  // 定时器默认为false,不启动
        repeat: true // 循环定时器
        interval: 100 //时间间隔为 100毫秒
        onTriggered: {
            percent += 1;  // 每次percent+1
            canvas.requestPaint(); // 重新绘制
            if (percent == 100) { // 如果percent==100,则停止定时器
                running = false;
            }
        }
    }

    Text {
        width: 30
        height: 100
        anchors.centerIn: parent
        text: String("%1%").arg(percent)  // 中间显示当前的进度
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        color: "black"
        font.pixelSize: 30
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            runTimer.running = true;  // 点击屏幕的圆圈启动定时器,根据需要,在外侧启动定时器。
        }
    }
}

有疑问欢迎评论交流。
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值