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

发布于 2024-07-24 09:38:42 字数 56 浏览 5 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

新雨望断虹 2024-07-31 09:38:42

如果您只想要一个具有随机颜色的实心画笔,您可以尝试以下操作:

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

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));
萌梦深 2024-07-31 09:38:42

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

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);
伴随着你 2024-07-31 09:38:42

我建议获取足够的样本画笔列表,然后从中随机选择。

仅仅获得一种随机颜色就会产生糟糕的颜色,您可以轻松地设置一个大约 50 种颜色的列表,然后您可以在每次需要随机颜色时使用。

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.

悸初 2024-07-31 09:38:42

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文