【问题标题】:How to generate randomly colors that is easily recognizable from each other? [duplicate]如何随机生成易于相互识别的颜色? [复制]
【发布时间】:2016-09-11 01:47:56
【问题描述】:

我想为图表生成随机颜色,但我尝试的颜色无法识别,并且生成的颜色通常彼此相似。有可能创造出这样的颜色吗?

我的方法:

    public Color[] GenerateColors(int n)
    {
        Color[] colors = new Color[n];
        for (int i = 0; i < n; i++)
        {
            int R = rnd.Next(0, 250);
            int G = rnd.Next(0, 250);
            int B = rnd.Next(0, 250);

            Color color = Color.FromArgb(R, G, B);
            colors[i] = color;
        }
        return colors;
    }

【问题讨论】:

  • 在这种情况下,你最好不要使用随机的,而是使用某种模式
  • 请参阅here 了解色距的讨论。还请查看KnownColors
  • 谢谢@OldBoyCoder 文章很好地解释了问题并给出了很好的解决方案
  • 根据你需要多少颜色,你可以硬编码它们。 Cynthia Brewer 的ColorBrewer 被广泛用于生成易于区分的颜色方案以显示数据。选择数据的性质,选择数据类的数量,最后选择您喜欢的配色方案/调色板。复制这些十六进制值,将它们存储在列表或数组中,获利!

标签: c# winforms random colors


【解决方案1】:

这是一个RandomColors 类,它结合了TawOldBoyCoder 的建议。根据您要生成多少颜色,Generate 方法要么从 KnownColors 中挑选,要么生成随机的新颜色,其中使用最后一种颜色作为混合颜色。

public class RandomColors
{
    static Color lastColor = Color.Empty;

    static KnownColor[] colorValues = (KnownColor[]) Enum.GetValues(typeof(KnownColor));

    static Random rnd = new Random();
    const int MaxColor = 256;
    static RandomColors()
    {
        lastColor = Color.FromArgb(rnd.Next(MaxColor), rnd.Next(MaxColor), rnd.Next(MaxColor));
    }

    public static Color[] Generate(int n)
    {
        var colors = new Color[n];
        if (n <= colorValues.Length)
        {
            // known color suggestion from TAW
            // https://stackoverflow.com/questions/37234131/how-to-generate-randomly-colors-that-is-easily-recognizable-from-each-other#comment61999963_37234131
            var step = (colorValues.Length-1) / n;
            var colorIndex = step;
            step = step == 0 ? 1 : step; // hacky
            for(int i=0; i<n; i++ )
            {
                colors[i] = Color.FromKnownColor(colorValues[colorIndex]);
                colorIndex += step;
            }
        } else
        {
            for(int i=0; i<n; i++)
            {
                colors[i] = GetNext();
            }
        }

        return colors;
    }

    public static Color GetNext()
    {
        // use the previous value as a mix color as demonstrated by David Crow
        // https://stackoverflow.com/a/43235/578411
        Color nextColor = Color.FromArgb(
            (rnd.Next(MaxColor) + lastColor.R)/2, 
            (rnd.Next(MaxColor) + lastColor.G)/2, 
            (rnd.Next(MaxColor) + lastColor.B)/2
            );
        lastColor = nextColor;
        return nextColor;
    }
}

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 2016-02-04
    • 2010-12-07
    • 2023-01-05
    • 2013-12-31
    • 1970-01-01
    • 2013-10-02
    • 2012-06-13
    相关资源
    最近更新 更多