Multiple Line Drawing

Anticipation

Member
Joined
Jul 15, 2008
Messages
10
Programming Experience
Beginner
Hi,
I'm using the code
VB.NET:
       Sub PicCanvasMouseDown(sender As Object, e As MouseEventArgs)
		XPrev = e.X
		YPrev = e.Y
	End Sub
	
	Public Sub PicCanvasMouseUp(sender As Object, e As MouseEventArgs)
		XCur = e.X
		YCur = e.Y
	End Sub
	
	Public Sub PicCanvasPaint(sender As Object, e As PaintEventArgs)
		Dim p As New Pen(PenColour, PenWidth)
		Dim g As Graphics = e.Graphics 
		g.DrawLine(p, XPrev, YPrev, XCur, YCur)
		PicCanvas.Invalidate()
	End Sub
(With XPrev, YPrev, XCur, YCur all being declared earlier in the code) To draw lines on a picturebox when the mouse is Clicked, and released. The problem is, that it only draws one line, and then when i go to draw another, the old one dissapears. I presume this is because i'm using the same integer variables in all of them.

My question is this; How would i be able to draw more than one line with the same variables ?

Thanks
 
How would i be able to draw more than one line with the same variables ?
That is impossible with 4 Integer variables. Using Paint event only what you specify in code is drawn each time that event is raised. Call DrawLine method one time for each line you want to draw. You have to keep track of all Point coordinates, which can be done with arrays/collections. Another option instead of drawing in Paint event is to draw to a bitmap image that you display, if you draw to the same image previous drawn lines are of course retained.
 
VB.NET:
        private lines as new List(Of Point())()
        private draggingPoint as Point

        Sub PicCanvasMouseDown(sender As Object, e As MouseEventArgs)
		draggingPoint = new Point(e.X, e.Y)
	End Sub
	
	Public Sub PicCanvasMouseUp(sender As Object, e As MouseEventArgs)
                dim points() as Point = {draggingPoint, new Point(e.X, e.Y)}

                lines.add(points);
	End Sub
	
	Public Sub PicCanvasPaint(sender As Object, e As PaintEventArgs)
		Dim p As New Pen(PenColour, PenWidth)
		Dim g As Graphics = e.Graphics 
                
                for each line() as Point in lines
                        g.DrawLines(p, line)
                next

		PicCanvas.Invalidate()
	End Sub

I just typed this in the wysiwyg editor for post writing and didn't run it so I'm not too sure about the syntax, but the logic should be there.

This will even support multiple points lines. The lines "List of Point arrays" object contains arrays of points. The paint event handler goes through all those arrays of points and for each array and draws a line between them from first to last.

Also, I'm pretty sure the MouseUp event assures us that the MouseDown event has to be executed first, but just for safety, I would add some error handling in there.
 
Back
Top