Alaa Sadik
Alaa Sadik

Reputation: 1089

Not able to clear drawings in PictureBox using VB.NET

I use the following code to make simple free-hand (brush) drawings over PictureBox1. Drawing is fine, but not able to clear the drawings I made permanently. If I click Button1 the drawings will be cleared, but once I move over PictureBox1 all old drawings (and PictureBox1 image) appear again. Any suggestions?

  Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown
        If e.Button = MouseButtons.Left Then
            mousePath.StartFigure()
        End If
  End Sub

Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
        '// slide annotations 
        If e.Button = MouseButtons.Left Then
               Try
            mousePath.AddLine(e.X, e.Y, e.X, e.Y)    'Add mouse coordiantes to mousePath
             Catch
             End Try
        End If
       PictureBox1.Invalidate()
    End Sub

 Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        '// slide annotations 
        Try
            '// drwaing options
            myUserColor = System.Drawing.Color.Red
            myAlpha = 255
            myPenWidth = 3
            CurrentPen = New Pen(myUserColor, myPenWidth)
            e.Graphics.DrawPath(CurrentPen, mousePath)
        Catch
        End Try
    End Sub

Private Sub Button1_Click_2(sender As Object, e As EventArgs) Handles Button1.Click
        Dim g As Graphics
        g = PictureBox1.CreateGraphics()
        g.Clear(PictureBox1.BackColor)
        g.Dispose()
    End Sub

Upvotes: 0

Views: 548

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

NEVER call CreateGraphics. ALWAYS do ALL your drawing in the Paint event handler. Your are creating a Graphics object in your Click event handler and clearing that, but what use is that when you do the drawing again in Paint event handler the next time that event is raised?

What you need to do is store all the data that represents your drawing in one or more fields, update that data whenever you want to change the drawing and draw using that data in the Paint event handler. If you want to clear the drawing, you clear that data and then force a repaint by calling Invalidate. In your Paint event handler you are drawing a GraphicsPath stored in the mousePath field. That means that, in your Click event handler, you need to clear that GraphicsPath and then call Invalidate. That will then prompt a Paint event that will first clear the existing drawing and then do the new. As there is no new to do, it will remain clear.

Upvotes: 1

Related Questions