tags:

views:

129

answers:

2

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!

+1  A: 

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.

MusiGenesis
Got it! Bit slower, but if I minimize the window it goes WAY faster. Considering it has to draw 30,000 pixels INDIVIDUALLY, 3 seconds isnt bad.
Cyclone
If you're drawing pixel-by-pixel, a faster but slightly more complicated technique is to call the LockBits method on the Bitmap. See http://www.vb-helper.com/howto_net_lockbits_image_class.html or http://www.bobpowell.net/lockingbits.htm
MusiGenesis
I was using SetPixel, which was quite slow as you can imagine, especially cause I added some application.doevents() to it lol
Cyclone
Time optimized to 1.4 seconds! Yay :P
Cyclone
A: 

Hi MusiGenesis 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()
SoloHere