Forcing a PictureBox to retain its image if the image was drawn on using code in vb.net

StackOverflow https://stackoverflow.com/questions/1529211

  •  20-09-2019
  •  | 
  •  

Question

My pictureboxes sometimes clear of all drawings when they are done creating the image, or sometimes halfway through. Calling GC.Collect() before the drawing starts lets it draw MORE before it clears, but how can I stop it from clearing entirely?

This is in vb.net

Thanks!

Was it helpful?

Solution

An easy way to persist drawn images in .Net is to do the drawing onto a separate Bitmap object, and then set the PictureBox's Image property equal to the Bitmap, like this:

Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
    // draw whatever
}
pictureBox1.Image = bmp;

Sorry this is C#, but it should illustrate the principle OK.

Another way to persist drawn images is to do the drawing in the PictureBox's Paint event, but this means that your drawing code will execute every time the control needs to repaint itself (which occurs whenever another form is dragged over top of it etc.). The above method (setting the control's Image property) is simpler to do.

OTHER TIPS

In the above case, when "bmp" or "g" object goes out of scope and garbage collected, the picturebox image changes. I think the image is always reference copied. I tried bmp.clone to copy the image onto the picturebox but still when bmp is garbage collected, the picturebox image vanishes. In my case, I've a number of(determined at runtime) such images to be assigned to runtime created pictureboxes.

Dim bm As New Bitmap("C:\picture.bmp")
Dim thumb As New Bitmap(42, 30)
Dim g As Graphics = Graphics.FromImage(thumb)

g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
g.DrawImage(bm, New Rectangle(0, 0, 42, 30), New Rectangle(0, 0, bm.Width, _bm.Height), GraphicsUnit.Pixel)
pbxHead.Image = thumb.Clone()

g.Dispose()
bm.Dispose()
thumb.Dispose()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top