6

What is the best way to pick a random brush from the System.Drawing.Brushes collection in C#?

mafu
  • 31,798
  • 42
  • 154
  • 247
SBurris
  • 7,378
  • 5
  • 28
  • 36

4 Answers4

13

If you just want a solid brush with a random color, you can try this:

    Random r = new Random();
    int red = r.Next(0, byte.MaxValue + 1);
    int green = r.Next(0, byte.MaxValue + 1);
    int blue = r.Next(0, byte.MaxValue + 1);
    System.Drawing.Brush brush = new System.Drawing.SolidBrush(Color.FromArgb(red, green, blue));
jjxtra
  • 20,415
  • 16
  • 100
  • 140
3

For WPF, use reflection:

var r = new Random();
var properties = typeof(Brushes).GetProperties();
var count = properties.Count();

var colour = properties
            .Select(x => new { Property = x, Index = r.Next(count) })
            .OrderBy(x => x.Index)
            .First();

return (SolidColorBrush)colour.Property.GetValue(colour, null);
Hamiora
  • 561
  • 5
  • 5
2

I suggest getting a list of enough sample brushes, and randomly selecting from there.

Merely getting a random colour will yield terrible colours, and you could easily set up a list of maybe 50 colours that you could then use every time you need a random one.

ANeves
  • 6,219
  • 3
  • 39
  • 63
1

An obvious way is to generate a random number and then pick the corresponding brush.

ChrisW
  • 54,973
  • 13
  • 116
  • 224