QML Context2D как заполнить два эллипса разными цветами? - PullRequest
0 голосов
/ 20 июня 2020

Я хочу создать n сегментную цветовую полосу, конечные точки которой - полукруги. Вот мой код:

Файл main.qml

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ResultBar{
        anchors.centerIn: parent
        vmColorArray: ["#0000ff", "#00ff00", "#ff0000"];
        id: test;
    }

}

Файл ResultBar.qml

import QtQuick 2.0

Item {

    id: resultBar
    width: 200
    height: 20

    property var vmColorArray: [];

    Canvas {
        id: rightTip
        width: parent.width
        height: parent.height
        contextType: "2d"
        anchors.right: parent.right
        anchors.verticalCenter: parent.verticalCenter
        onPaint: {

            if (vmColorArray.length < 2) return;

            var ctx = rightTip.getContext("2d");
            ctx.reset();

            var y = 0;
            var n = vmColorArray.length;
            var w = width/n;

            // Left end
            ctx.ellipse(0,y,height,height);
            ctx.fillStyle = vmColorArray[0];
            ctx.fill();
            ctx.closePath();

            // Right end
            ctx.ellipse(width-height,y,height,height);
            ctx.fillStyle = vmColorArray[n-1];
            ctx.fill();

            var x = 0;
            for (var i = 0; i < n; i++){

               if (i === 0) x = height/2;
               else x = i*w;

               var wd
               if (i === n-1) wd = w - height/2;
               else wd = w

               ctx.fillStyle = vmColorArray[i];
               ctx.fillRect(x,y,wd,height)
            }

        }
    }
}

Моя проблема в том, что раскрашивание правого края ТАКЖЕ окрашивает левый конец. Вот как это выглядит:

введите описание изображения здесь

Итак, мой вопрос: как мне указать холсту заполнить один из кругов и ЗАТЕМ заполнить другой, не заполняя предыдущий?

1 Ответ

0 голосов
/ 20 июня 2020

Я понял. Копирование ТОЛЬКО соответствующего кода:

        // Left end
        ctx.fillStyle = vmColorArray[0];
        ctx.ellipse(0,y,height,height);
        ctx.fill();
        //ctx.closePath();

        // Right end
        ctx.beginPath()
        ctx.fillStyle = vmColorArray[n-1];
        ctx.ellipse(width-height,y,height,height);
        ctx.fill();

Ключ должен был начать новый путь !! Надеюсь, это кому-то поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...