Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to pick 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#?

like image 509
SBurris Avatar asked Jun 18 '09 03:06

SBurris


4 Answers

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);
like image 43
Hamiora Avatar answered Oct 21 '22 17:10

Hamiora


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));
like image 131
jjxtra Avatar answered Oct 21 '22 16:10

jjxtra


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.

like image 27
ANeves Avatar answered Oct 21 '22 17:10

ANeves


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

like image 1
Aad Mathijssen Avatar answered Oct 21 '22 18:10

Aad Mathijssen