What is the best way to choose a random brush from the Brushes collection in C #?

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

+6
collections c # select
source share
4 answers

If you need a solid brush with a random color, you can try the following:

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)); 
+13
source share

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); 
+3
source share

I suggest getting a list of sufficient brush samples and randomly picking from there.

Just getting a random color will result in terrible colors, and you can easily customize a list of 50 colors that you could use every time you need a random one.

+2
source share

The obvious way is to create a random number and then select the appropriate brush.

+1
source share

All Articles