Drawing event draws two object

2019-09-05 05:15发布

问题:

Program has only this code.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    PictureBox1.Image = PictureBox2.Image
    Dim g As Graphics = Graphics.FromImage(PictureBox1.Image)
    g.DrawEllipse(New Pen(Color.MediumOrchid, 5), 30, 30, 30, 30)
    g.Dispose()
    PictureBox1.Refresh()
    PictureBox2.Refresh()
End Sub

Before clicking PictureBox1 is emtpty and PictureBox2has a white image.

After clicked PictureBox1 and PictureBox2 both have ellipse.

I think program uses one image for two pictureBox'es.So when I paint they are both painted.I want to set picbox2 white image and picbox1 white image with ellipse.Any solution ?

回答1:

You have to make a copy of the image, so you will use the same data, but not the same object, and so are safe from changes on the original object.

I am not a vb.net expert, but you may try this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
    Button1.Click
    PictureBox1.Image = New Bitmap(PictureBox2.Image)
    Dim g As Graphics = Graphics.FromImage(PictureBox1.Image)
    g.DrawEllipse(New Pen(Color.MediumOrchid, 5), 30, 30, 30, 30)
    g.Dispose()
    PictureBox1.Refresh()
    PictureBox2.Refresh()
End Sub