QML Context2D如何用不同的颜色填充两个椭圆?
我想创建一个n段颜色条,其端点是半圆。以下是我目前的代码: 文件main.qmlQML Context2D如何用不同的颜色填充两个椭圆?,qml,Qml,我想创建一个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 vmCol
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)
}
}
}
}
导入QtQuick 2.0
项目{
id:resultBar
宽度:200
身高:20
属性变量vmColorArray:[];
帆布{
id:rightTip
宽度:parent.width
高度:parent.height
上下文类型:“2d”
anchors.right:父项.right
anchors.verticalCenter:父级.verticalCenter
onPaint:{
if(vmColorArray.length<2)返回;
var ctx=rightip.getContext(“2d”);
ctx.reset();
var y=0;
var n=vmColorArray.length;
var w=宽度/n;
//左端
椭圆(0,y,高度,高度);
ctx.fillStyle=vmColorArray[0];
ctx.fill();
ctx.closePath();
//右端
ctx.椭圆(宽-高,y,高,高);
ctx.fillStyle=vmColorArray[n-1];
ctx.fill();
var x=0;
对于(变量i=0;i
我的问题是,给右端上色也会给左端上色。下面是它的外观:
因此,我的问题是,如何让画布填充其中一个圆,然后填充另一个圆,而不重新填充上一个圆?我已经找到了答案。仅复制相关代码:
// 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();
关键是开始一条新的道路!!希望这对别人有帮助