【问题标题】:How do I pick nice random colors when drawing a chart?绘制图表时如何选择漂亮的随机颜色?
【发布时间】:2012-03-22 18:26:02
【问题描述】:

我需要一些随机的颜色来画一个馅饼。我的代码有效,但它可以一次又一次地采用相同的颜色

    Random r = new Random();

    for (int i = 0; i < 20; i++)
    {
        int min = 0;
        int max = 255;
        int rand1 = r.Next(min, max);
        int rand2 = r.Next(min, max);
        int rand3 = r.Next(min, max);
        Color myColor = Color.FromArgb(rand1, rand2, rand3);  
        //drawing the pie here
   }

我怎样才能重做它,使它不会再次选择相同的颜色。

【问题讨论】:

  • 这是 Java 吗?请正确标记。
  • 也许随机生成器需要一个种子号,例如时间戳
  • 它在 asp.net 中的 C#,我尝试设置种子编号没有帮助
  • 关于正确的Random:stackoverflow.com/a/768001/90674

标签: c# asp.net random colors


【解决方案1】:

通常最好先创建一些漂亮的调色板,然后从调色板中挑选颜色。在伪代码中:

var Palette = new Array(Color(r1, g1, b1), Color(r2, g2, b2), …);
for (var i=0; i<numberOfPieSegments; i++)
    drawPieSegment(Palette[i % Palette.length], …);

【讨论】:

  • 这是一个很好的解决方案,但有时颜色量很大并且手动创建它需要随机生成器节省我们的时间
【解决方案2】:

您可以将生成的随机颜色放入容器中,然后检查容器中是否已插入某个 delta 的相似颜色

这样您就不会冒险选择不同但非常相似的颜色,例如: RGB(0, 0, 0)RGB(10, 2, 3)

const int DELTA_PERCENT = 10;
List<Color> alreadyChoosenColors = new List<Color>();

// initialize the random generator
Random r = new Random();

for (int i = 0; i < 20; i++)
{
    bool chooseAnotherColor = true;      
    while ( chooseAnotherColor )
    {
       // create a random color by generating three random channels
       //
       int redColor = r.Next(0, 255);
       int greenColor = r.Next(0, 255);
       int blueColor = r.Next(0, 255);
       Color tmpColor = Color.FromArgb(redColor, greenColor, blueColor);  

       // check if a similar color has already been created
       //
       chooseAnotherColor = false;
       foreach (Color c in alreadyChoosenColors)
       {
          int delta = c.R * DELTA_PERCENT / 100;
          if ( c.R-delta <= tmpColor.R && tmpColor.R <= c.R+delta )
          {
             chooseAnotherColor = true;
             break;
          }

          delta = c.G * DELTA_PERCENT / 100;
          if ( c.G-delta <= tmpColor.G && tmpColor.G <= c.G+delta )
          {
             chooseAnotherColor = true;
             break;
          }

          delta = c.B * DELTA_PERCENT / 100;
          if ( c.B-delta <= tmpColor.B && tmpColor.B <= c.B+delta )
          {
             chooseAnotherColor = true;
             break;
          }
        }
    }

    alreadyChoosenColors.Add(tmpColor);
    // you can safely use the tmpColor here

   }

【讨论】:

  • 我已经无法获取 ListChoosenColors = new ArrayList();上班
【解决方案3】:

查看 descripton of Random class 的 msdn,检查一下:但是,由于时钟的分辨率有限,使用无参数构造函数来创建不同的 Random 对象,从而创建产生相同随机数序列的随机数生成器。
因此,您应该每次使用不同的种子来初始化 Random 实例。我推荐时间戳。

【讨论】:

  • 这不是这里发生的事情。 OP 仅构建 Random 的一个实例并使用它。 OP 可能会选择相似的颜色(即使数字不同,看起来也一样)。
猜你喜欢
  • 2011-03-14
  • 2016-10-17
  • 1970-01-01
  • 2013-03-26
  • 2019-10-29
  • 2021-09-29
  • 1970-01-01
  • 2014-10-12
  • 2019-03-29
相关资源
最近更新 更多