Canvas(四-绘图程序)

创建四个颜色盒子,然后将这四个盒子装在 Row 定位器中,Row 定位器保存一个变量,此变量保存用户通过点击这四个盒子决定的颜色值!

ColorSquare组件:

import QtQuick 2.5

Rectangle {
    id: root
    width: 48; height: 48
    color: "green"
    signal clicked
    property bool active: false
    border.color: active? "#666666" : "#f0f0f0"
    border.width: 2

    MouseArea {
        id: area
        anchors.fill :parent
        onClicked: {
            root.clicked()
        }
    }
}
        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 {
                    id: red
                    color: modelData
                    active: parent.paintColor == color
                    onClicked: {
                        // 盒子响应点击信号,
                        // 设置 parent.paintColor 的值
                        parent.paintColor = color
                    }
                }
            }
        }

当我们点击鼠标的时候,会将鼠标的坐标保存在程序中,当移动鼠标的时候会触发 onPaint 绘制窗口(根据更新之后的鼠标位置)

原理代码:

            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()
                }
            }

原理代码解析:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sssnial-jz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值