天天看點

QT定制波浪進度條基于QML

示範效果:

外邊框,内部水波浪進度顔色,進度百分比與顔色能自定義 

QT定制波浪進度條基于QML

進度條相關數值 

QT定制波浪進度條基于QML

 外圈繪制

QT定制波浪進度條基于QML

 繪制波浪

QT定制波浪進度條基于QML

剪切為圓形

QT定制波浪進度條基于QML
import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 400
    height: 300
    color:"black" //視窗背景
    title: qsTr("QT定制波浪進度條基于QML")

    property int rangeValue: 68; //水波浪最大進度值
    property int nowRange: 0;//水波浪預設進度值

    //畫布大小與畫布邊框大小
    property int w: 250;//寬
    property int h: 250;//高
    property int lineWidth: 2;//邊框

    //圓
    property double r: h / 2; //圓垂直方向中心
    property double cR: r - 16 * lineWidth; //圓半徑

    //Sin曲線
    property int sX: 0;
    property int sY: h / 2;
    property int axisLength: w;        //軸長
    property double waveWidth: 0.015;   //波浪寬度,數越小越寬
    property double waveHeight: 6;      //波浪高度,數越大越高
    property double speed: 0.09;        //波浪速度,數越大速度越快
    property double xOffset: 0;         //波浪x偏移量

    Canvas{
        id: canvas
        width: w
        height: h
        anchors.centerIn: parent
        onPaint: {
            var ctx = getContext("2d");//取得2d繪圖上下文
            ctx.clearRect(0, 0, w, h);//清空區域
            //繪制進度條外圈
            ctx.beginPath();//開始繪制
            ctx.strokeStyle = 'red';
            ctx.arc(r, r, cR+5, 0, 2*Math.PI);
            ctx.stroke();//結束繪制


            ctx.beginPath();
            ctx.arc(r, r, cR, 0, 2*Math.PI);
            ctx.clip();

            //繪制sin曲線
            ctx.save();
            var points=[];
            ctx.beginPath();
            for(var x = sX; x < sX + axisLength; x += 20 / axisLength){
                var y = -Math.sin((sX + x) * waveWidth + xOffset);
                var dY = h * (1 - nowRange / 100 );
                points.push([x, dY + y * waveHeight]);
                ctx.lineTo(x, dY + y * waveHeight);
            }

            //繪制波浪
            ctx.lineTo(axisLength, h);
            ctx.lineTo(sX, h);
            ctx.lineTo(points[0][0],points[0][1]);
            ctx.fillStyle = '#ff00ff';
            ctx.fill();
            ctx.restore();

            //繪制百分數文字
            ctx.save();
            var size = 0.4*cR;
            ctx.font = size + 'px Arial';//字型大小
            ctx.textAlign = 'center';//居中
            ctx.fillStyle = "rgba(255, 255, 255, 0.8)";//字型顔色
            ctx.fillText(~~nowRange + '%', r, r + size / 2);//根據進度顯示文本
            ctx.restore();

            //增加Rang值
            if(nowRange <= rangeValue){
                nowRange += 1;
            }

            if(nowRange > rangeValue){
                nowRange -= 1;
            }
            xOffset += speed;
        }

        Timer{
            id: timer
            running: true //預設啟動計時器
            repeat: true //重複
            interval: 5 //計時器響應時間
            onTriggered:{
                parent.requestPaint();//請求視窗重新繪制,視窗會調用onPaint函數
            }
        }
    }

}      

繼續閱讀