Search code examples
c#.netgdi+lineargradientbrushdrawing2d

How to change colors of a GDI+ LinearGradientBrush?


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


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