【问题标题】:Not able to clear drawings in PictureBox using VB.NET无法使用 VB.NET 清除 PictureBox 中的绘图
【发布时间】:2023-03-27 08:58:03
【问题描述】:

我使用以下代码在 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】:

切勿致电CreateGraphics。始终在 Paint 事件处理程序中完成所有绘图。您正在Click 事件处理程序中创建一个Graphics 对象并清除它,但是当您在下次引发该事件时在Paint 事件处理程序中再次进行绘图时有什么用?

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

【讨论】:

    猜你喜欢
    • 2012-07-15
    • 2015-12-21
    • 2021-05-07
    • 2022-01-20
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多