Today I am faced with a dilemma. I created an application that uses GDI + to draw on a form. The drawing is started by a timer every second. The draw method uses a for loop to iterate over a set of objects, and if they have a certain state, draw them.
I want to paint them with LinearGradientBrush simply because it looks much better than a simple brush. Look at the following
//minutes foreach (Led l in MinuteGrid.Leds) { LinearGradientBrush b = new LinearGradientBrush (l.LedRectangle, Color.GreenYellow, Color.Green, 110); if (l.IsLit) g.FillRectangle(b, l.LedRectangle); b.Dispose(); }
I create a new LinearGradientBrush for each iteration of the loop (which bothers me), but that is because I have to. I cannot create one outside the loop because its set of constructors requires me to set parameters that are only ever known inside the loop.
I found that using the dispose method on a LinearGradientBrush object is not so reliable. If I run the application and view it in the task manager, its memory will be ejected. When I then add the line b = null, which seems to be very helpful as follows
foreach (Led l in MinuteGrid.Leds) { LinearGradientBrush b = new LinearGradientBrush (l.LedRectangle, Color.GreenYellow, Color.Green, 110); if (l.IsLit) g.FillRectangle(b, l.LedRectangle); if (b != null) { b.Dispose(); b = null; } }
I'm just wondering if there is a better way to work with LinearGradientBrushes? Or is there a better solution to use?
Many thanks
c # gdi +
Kieran
source share