简体   繁体   English

从C#中的Brushes集合中选择随机画笔的最佳方法是什么?

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

从C#中的System.Drawing.Brushes集合中选择随机画笔的最佳方法是什么?

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

For WPF, use reflection: 对于WPF,使用反射:

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

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. 仅仅获得随机颜色会产生可怕的颜色,您可以轻松设置50种颜色的列表,然后您可以在每次需要随机颜色时使用这些颜色。

一种显而易见的方法是生成一个随机数,然后选择相应的画笔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM