Drawing Line on MS Paint Style
-
Good evening, I'm new to QML and I'm really having some trouble with QML Canvas. I'm currently working on a project that the draw some linear lines, like in MS Paint, but I don't know how to start developing that part... Can anyone give me some light on this issue?
OBS.: Sorry for my poor english
-
@jvaesteves I hope you have already looked into Canvas.
So basically to paint using Canvas you have to override the onPaint handler. Then using its methods you can draw whatever you like. Most of the methods conform to the HTML's Canvas specifications. For eg. to draw lines you can uselineTo
andmoveTo
and then finallystroke
. Following example might give you a basic understandingimport QtQuick 2.4 Canvas { id: root width: 200 height: 200 onPaint: { var ctx = getContext("2d") ctx.lineWidth = 2 ctx.strokeStyle = "blue" ctx.moveTo(0,0) ctx.lineTo(200,200) ctx.stroke() } }
You can find explanation for
getContext
in the docs.
Hope it helps... -
I think I didn't express myself well. What I want is the user doing all the drawing, your example just draws a static line on predefined coordinates.
Here is an example on HTML5 Canvas: https://dev.opera.com/articles/html5-canvas-painting/example-5.html
-
@jvaesteves I thought so ;)
You just need to add couple of extra lines of code to it. Define a MouseArea, implementonPressed
andonPositionChanged
handlers where you store initial and final points of the line. Then after getting the final point justrequestPaint
forCanvas
. Be sure to clear theCanvas
before each update. -
@jvaesteves I was able to reproduce following according to their source.
import QtQuick 2.4 Canvas { id: root width: 200 height: 200 property point initialpos : Qt.point(0,0) property point finalpos: Qt.point(0,0) onPaint: { var ctx = getContext("2d") ctx.clearRect(0, 0, width, height); ctx.lineWidth = 2 ctx.strokeStyle = "red" ctx.beginPath() ctx.moveTo(initialpos.x,initialpos.y) ctx.lineTo(finalpos.x,finalpos.y) ctx.stroke() ctx.closePath() } MouseArea { anchors.fill: parent onPressed: initialpos = Qt.point(mouseX,mouseY) onPositionChanged: { finalpos = Qt.point(mouseX,mouseY) root.requestPaint() } } }
I'm pretty sure you can find way to draw multiple lines too.
-
Kimmo Lindholm wrote a very nice Paint app for the Jolla which is open source, and uses this technique (but it's far more complicated since it offers a bunch of different modes and features too): https://github.com/kimmoli/paint/blob/master/qml/pages/Paint.qml