Question

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 :)

Was it helpful?

Solution

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 };

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top