学习书籍:
- 《QmlBook》
Qt 版本:Qt 5.12.10
Qt Quick 也提供了最为基本的绘制工具,Canvas
元素提供了最基本的画布,用户就在这个画布上画点线面即可,比如下面就填充了一个方形:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import QtQuick 2.5
Canvas { id: root width: 200; height: 200 onPaint: { var ctx = getContext("2d") ctx.lineWidth = 4 ctx.strokeStyle = "blue" ctx.fillStyle = "red" ctx.beginPath() ctx.moveTo(50,50) ctx.lineTo(150,50) ctx.lineTo(150,150) ctx.lineTo(50,150) ctx.closePath() ctx.fill() ctx.stroke() } }
|
基本流程
在Canvas
中绘图,其坐标(0,0)默认是在左上角,并且 x 是从左到右增加,y 是从上到下增加。
绘制最基本的线条的基本流程是:
- 设置线宽(lineWidth)、线颜色(strokeStyle)、填充颜色(fillStyle)等
- 启动绘制(beginPath)
- 设置起始点(moveTo)
- 按照坐标进行绘制
- 结束绘制(closePath)
- 使能填充(fill)及外框绘制(stroke)
除了基本线条,Qt Quick 还提供了很多常用图形的绘制,比如矩形:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import QtQuick 2.12
Canvas { id: root width: 200; height: 200 onPaint: { var ctx = getContext("2d") ctx.fillStyle = 'green' ctx.strokeStyle = "blue" ctx.lineWidth = 4 ctx.fillRect(20, 20, 80, 80) ctx.clearRect(30,30, 60, 60) ctx.strokeRect(20,20, 40, 40) } }
|
渐变色
在画布上画渐变色:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import QtQuick 2.12
Canvas { id: root width: 200; height: 200 onPaint: { var ctx = getContext("2d") var gradient = ctx.createLinearGradient(100,0,100,200) gradient.addColorStop(0, "blue") gradient.addColorStop(0.5, "lightsteelblue") ctx.fillStyle = gradient ctx.fillRect(50,50,100,100) } }
|
阴影
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import QtQuick 2.12
Canvas { id: root width: 300; height: 200 onPaint: { var ctx = getContext("2d") ctx.strokeStyle = "#333" ctx.fillRect(0,0,root.width,root.height);
ctx.shadowColor = "#2ed5fa"; ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; ctx.shadowBlur = 10;
ctx.font = 'bold 80px 方正姚体'; ctx.fillStyle = "#24d12e"; ctx.fillText("Canvas!",30,180); } }
|
Canvas 还支持缩放、旋转等,基本上 QPaint 有的它都有,其它的东西在需要使用的时候再来了解吧。