QML_Canvas画布
说明:
Canvas 是 QML 自带的一个类型,它提供了一个 2D 画布,允许程序员通过 JavaScript 进行绘图。
Context2D 也是 QML 自带的类型,提供了一些绘制 2D 形状的方法用于 Canvas 上面。
先看效果图:
源码展示:
注意:资源图片(cricle.png)为了保证可以下载到原图,放在百度网盘中
链接:https://pan.baidu.com/s/1KMZ0tds52IUsmnHGG-hulA?pwd=t3x3 提取码:t3x3
–来自百度网盘超级会员V4的分享
import QtQuick 2.12
import QtQuick.Controls 2.13
import QtQuick.Window 2.12
Window {
width: 800
height: 480
visible: true
title: qsTr("环形显示进度")
color:"white"
Item {
id: root
width: 220
height: 220
anchors.centerIn: parent
property int maxvalue:100
property double nowvalue :30.0
Rectangle{
id:rect
width: parent.width
height: width
radius: width/2
antialiasing: true
anchors.centerIn: parent
color: "#00000000"
Text {
id: ratio
anchors.centerIn: parent
color: "blue"
text: String("%1%").arg(root.nowvalue.toFixed(2))//toFixed是保留两位小数
font{
pointSize: 30
family: "黑体"
}
}
Image {
id: background
anchors.fill: parent
source: "/images/cricle.png"
}
Canvas{
id:canvas
anchors.fill: parent
antialiasing: true//抗锯齿效果,会带来更大的内存开销
onPaint: {
var ctx = getContext("2d")
//绘图之前清除画布
ctx.clearRect(0,0,width,height)
ctx.lineCap = "round"
ctx.strokeStyle = "rgb(26,134,255)"
ctx.lineWidth = 20
ctx.beginPath()
ctx.arc(rect.width/2,rect.height/2,rect.width/2-ctx.lineWidth+10,-Math.PI/2,-Math.PI/2+root.nowvalue/root.maxvalue*2*Math.PI )
ctx.stroke()
}
}
}
Slider {
id: slider
anchors.top:root.bottom
width: root.width
to:100
from:0
value: root.nowvalue //默认值
stepSize: 0.01 //步进值
onValueChanged: {
root.nowvalue = value
canvas.requestPaint()//重画更新环形进度条
console.log(value)
}
}
}
}