开发者

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜