Qt6 QML Book/画布/画布绘制

Canvas Paint

画布绘制

In this example, we will create a small paint application using the Canvas element.

在本例中,我们将使用Canvas元素类型创建一个小的绘画应用程序。

Qt6 QML Book/画布/画布绘制

For this, we arrange four color squares on the top of our scene using a row positioner. A color square is a simple rectangle filled with a mouse area to detect clicks.

为此,我们使用行定位器在场景顶部排列四个彩色正方形。彩色方块是一个简单的矩形,填充鼠标区域以检测点击。

Row {
    id: colorTools
    anchors {
        horizontalCenter: parent.horizontalCenter
        top: parent.top
        topMargin: 8
    }
    property color paintColor: "#33B5E5"
    spacing: 4
    Repeater {
        model: ["#33B5E5", "#99CC00", "#FFBB33", "#FF4444"]
        ColorSquare {
            color: modelData
            active: parent.paintColor == color
            onClicked: {
                parent.paintColor = color
            }
        }
    }
}

The colors are stored in an array and the paint color. When one the user clicks in one of the squares the color of the square is assigned to the paintColor property of the row named colorTools.

颜色存储在一个数组中,并且绘制颜色。当用户单击其中一个方块时,方块的颜色将指定给名为colorTools的行的paintColor属性。

To enable tracking of the mouse events on the canvas we have a MouseArea covering the canvas element and hooked up the pressed and position changed handlers.

为了能够在画布上跟踪鼠标事件,我们有一个覆盖画布元素的MouseArea,并连接了按下和位置更改的处理器。

Canvas {
    id: canvas
    anchors {
        left: parent.left
        right: parent.right
        top: colorTools.bottom
        bottom: parent.bottom
        margins: 8
    }
    property real lastX
    property real lastY
    property color color: colorTools.paintColor

    onPaint: {
        var ctx = getContext('2d')
        ctx.lineWidth = 1.5
        ctx.strokeStyle = canvas.color
        ctx.beginPath()
        ctx.moveTo(lastX, lastY)
        lastX = area.mouseX
        lastY = area.mouseY
        ctx.lineTo(lastX, lastY)
        ctx.stroke()
    }
    MouseArea {
        id: area
        anchors.fill: parent
        onPressed: {
            canvas.lastX = mouseX
            canvas.lastY = mouseY
        }
        onPositionChanged: {
            canvas.requestPaint()
        }
    }
}

A mouse press stores the initial mouse position into the lastX and lastY properties. Every change on the mouse position triggers a paint request on the canvas, which will result in calling the onPaint handler.

按下鼠标将初始鼠标位置存储到lastX和lastY属性中。鼠标位置的每次更改都会触发画布上的绘制请求,这将导致调用onPaint处理程序。

To finally draw the users stroke, in the onPaint handler we begin a new path and move to the last position. Then we gather the new position from the mouse area and draw a line with the selected color to the new position. The mouse position is stored as the new last position.

为了最终绘制用户轨迹,在onPaint处理器中,我们开始一个新路径并移动到最后一个位置。然后我们从鼠标区域收集新位置,并用选定的颜色绘制一条线到新位置。鼠标位置存储为新的最后位置。

  示例源码下载 

上一篇:技术周刊2020-09-21


下一篇:canvas小程序