无法使用VB.NET清除PictureBox中的图形

问题描述 投票:0回答:1

我使用以下代码在PictureBox1上制作简单的手绘图(画笔)。图纸还可以,但无法清除我永久制作的图纸。如果单击Button1,图形将被清除,但是一旦我移到PictureBox1,所有旧图形(和PictureBox1图像)将再次出现。有什么建议吗?

  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
vb.net visual-studio graphics drawing picturebox
1个回答
0
投票

从不拨打CreateGraphics。始终在Paint事件处理程序中完成所有绘图。您正在Graphics事件处理程序中创建Click对象并清除该对象,但是当您下次在该事件发生时再次在Paint事件处理程序中进行绘制时,有什么用?

[您需要做的是将代表图形的所有数据存储在一个或多个字段中,每当您想要更改图形并在Paint事件处理程序中使用该数据进行绘制时,都应更新该数据。如果要清除图形,请清除该数据,然后通过调用Invalidate强制重新绘制。在Paint事件处理程序中,您正在绘制存储在GraphicsPath字段中的mousePath。这意味着,在Click事件处理程序中,需要清除该GraphicsPath,然后调用Invalidate。然后,将提示一个Paint事件,该事件将首先清除现有图形,然后执行新的图形。由于没有新的工作要做,因此将保持清晰。

© www.soinside.com 2019 - 2024. All rights reserved.