By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,979 Members | 943 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,979 IT Pros & Developers. It's quick & easy.

Disposing of Bitmap

P: n/a
Hi,

Objective:
Draw a grid on a bitmap and set this as a panel's image. (Rather than
draw the grid directly on the panel and redraw repeatedly in the paint
event.)

Problem:
It works fine. I'm just not sure about disposing of the objects. I've
tried a variety of approaches but I find that when I redraw repeatedly
(just for testing) I get memory creep.
[I've recently moved to VB.Net from VB6 - head hurty.]

Question:
How should I be disposing of the bitmap to prevent the memory creep.

Thanks in advance.
Gman

Code as follows:
'This app is one form, with one panel and one button - that's it. Only
code is that which is below.

'Declare with form/class scope so I can easily dispose of it.
Private m_bmp As Bitmap

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

' Dispose of any existing bitmap
If Not m_bmp Is Nothing Then m_bmp.Dispose()

'create a bitmap that is the same size as the panel
'(it may have been resized)
m_bmp = New Bitmap(Panel1.Width, Panel1.Height)
Dim gfx As System.Drawing.Graphics = Graphics.FromImage(m_bmp)
Dim myPen As New System.Drawing.Pen(Color.Blue)

' Calculate the span of the lines
Dim iLinesInc As Integer = Panel1.Width \ 10
' Draw the lines on the bitmap
Dim i As Integer
For i = iLinesInc To Panel1.Width - iLinesInc Step iLinesInc
gfx.DrawLine(myPen, i, 0, i, Panel1.Height)
Next i

' Dispose of the old image
If Not Panel1.BackgroundImage Is Nothing Then _
Panel1.BackgroundImage.Dispose()
' Load the new bitmap into the panel
Panel1.BackgroundImage = m_bmp

' Tidy up
gfx.Dispose()
myPen.Dispose()
'm_bmp.Dispose() 'we can't dispose of it here

End Sub
Feb 16 '06 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.