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

五迷三道 提交于 2020-01-01 05:16:12

问题


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


回答1:


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



回答2:


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:


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.




回答4:


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



来源:https://stackoverflow.com/questions/1010638/what-is-the-best-way-to-pick-a-random-brush-from-the-brushes-collection-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!