views:

80

answers:

2

I have to write several small vertical gradients (on a loop) and so I think it's faster to re-use an existing LinearGradientBrush (correct?)

But this isn't what I expected to happen...

  Drawing2D.LinearGradientBrush myBrush = new Drawing2D.LinearGradientBrush(new Rectangle(0, 0, 200, 200), Color.Red, Color.Black, Drawing2D.LinearGradientMode.Vertical);
  myBrush.LinearColors[1] = Color.Blue;
  MsgBox(myBrush.LinearColors[1].ToString); //Returns black

So, is there either an error on the above code, or a better way to get several vertical gradients on a loop, or a different way to change the LinearGradientBrush's colors?

Thanks :)

+1  A: 

Constructing a brush costs almost nothing compared to the work done to actually draw something with the brush.

Also, try setting the entire array instead of replacing a single element.

myBrush.LinearColors = new Color[2] { Color.Blue, Color.Whatever };
Steve
So creating a new LinearGradientBrush is almost the same as replacing its colors?
Camilo Martin
I wrote a very interactive retail graphical application and found that creating new brushes didn't significantly impact performance when measured with dotTrace (which i would HIGHLY recommend for anyone writing applications that make heavy use of GDI+ or WPF)
Steve
Setting the entire array worked, and I'll use that! Dumb me for not thinking about it earlier. Thanks! :)
Camilo Martin
+1  A: 

This is perhaps academic (and perhaps much of it is obvious in retrospect!), but the reason changing a single color doesn't work is that the colors are extracted from non-managed code before being presented to you - you are given a copy of the color and that is what you are changing. Or, to put it more formally, the l-value in your statement is passed by value and there is no mechanism for updating the original.

When you change the whole gradient array the property setter for the array writes the changes back to the unmanaged object.

Bob Sammers
Thanks for the info - I really didn't knew that. Now that I think about it, it does make sense that working on the array is actually getting a copy of the array and then working on the copy. :/
Camilo Martin