【问题标题】:Why is a painted dot disappears sometime?为什么画的点有时会消失?
【发布时间】:2019-11-14 12:40:37
【问题描述】:

我尝试在图像上画一个点 …

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            PictureBox1.Image = Image.FromFile("C:\Users\SHEMMY-7X64\Pictures\postage.jpg")
            Using p As New System.Drawing.Pen(Color.Yellow, 4)
                Using g As Graphics = PictureBox1.CreateGraphics()
                    g.DrawEllipse(p, 15, 5, 10, 10)
                End Using
            End Using
        End Sub

图像是绘制的,但不是点。 将代码分为两个步骤时: 1.加载图片

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PictureBox1.Image = Image.FromFile("C:\Users\SHEMMY-7X64\Pictures\postage.jpg")
    End Sub

2。油漆

 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Using p As New System.Drawing.Pen(Color.Yellow, 4)
            Using g As Graphics = PictureBox1.CreateGraphics()
                g.DrawEllipse(p, 15, 5, 10, 10)
            End Using
        End Using

    End Sub

这次画了点。 我在另一个网站上发布了这个问题,并被告知这是一个时间问题。

好的,这是时间问题,但是如何解决呢?

【问题讨论】:

  • 永远不要打电话给CreateGraphics。始终使用提供的Graphics 对象在其Paint 事件处理程序中绘制控件。每次引发Paint 事件时,在控件上绘制的任何内容都会被删除。如果您希望绘图是永久性的,您必须在每个Paint 事件上重做它。

标签: vb.net paint


【解决方案1】:

您需要绘制包括图像在内的所有内容。你可以:

创建一个Bitmap 类型的类级变量并将其命名为Bmp:

Private Bmp as Bitmap

要加载新图像:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'dispose the old image if any:
    bmp?.Dispose()

    'and assing the new one:
    bmp = New Bitmap(Image.FromFile("C:\Users\SHEMMY-7X64\Pictures\postage.jpg"))

    'and call:
    PictureBox1.Invalidate()
End Sub

现在的绘画程序:

Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
    If bmp IsNot Nothing Then
        Dim srcRect As New Rectangle(0, 0, bmp.Width, bmp.Height)
        Dim desRect As New Rectangle(0, 0, PictureBox1.Width, PictureBox1.Height)
        Dim G As Graphics = e.Graphics

        G.SmoothingMode = SmoothingMode.AntiAlias

        G.Clear(BackColor) 'or: G.Clear(Parent.Backcolor) if you want.
        G.DrawImage(bmp, desRect, srcRect, GraphicsUnit.Pixel)

        Using pn As New Pen(Color.Yellow, 4)
            G.DrawEllipse(pn, 15, 5, 10, 10)
        End Using
    End If
End Sub

最后别忘了清理:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    bmp?.Dispose()
End Sub

祝你好运。

【讨论】:

  • 我尝试使用 pant 事件,它运行良好。谢谢JQSOFT
  • @shemmy 如果这回答了您的问题,您应该点击旁边的复选标记接受答案。
  • 是的,它绝对回答了我的问题
  • @shemmy Here 描述了您如何接受答案(并奖励 JQSOFT 为您提供帮助的时间)
猜你喜欢
  • 2014-09-30
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
相关资源
最近更新 更多