开发者

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

开发者 https://www.devze.com 2022-12-08 09:31 出处:网络
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 b

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!


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.


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消