【问题标题】:How to generate random color? [closed]如何生成随机颜色? [关闭]
【发布时间】:2012-06-13 01:04:23
【问题描述】:

所以我在 c# 中乱七八糟,想知道如何从数组中生成我的字符串,但颜色是随机的:

    while (true)
        {
            string[] x = new string[] { "", "", "" };
            Random name = new Random();
            Console.WriteLine((x[name.Next(3)]));
            Thread.Sleep(100);
        }

当我输出 x 时,我希望它是一种随机颜色。 谢谢

【问题讨论】:

  • 再解释一下就好了。例如。你期待"Red""#FF0000"ColorColors.Red 或..?是否有一组可能的值,或者您是否希望为 R、G 和 B 组件生成随机数,然后为此获取 Color 对象(不一定有一个好听的英文名称)?

标签: c# arrays colors


【解决方案1】:
// Your array should be declared outside of the loop

string[] x = new string[] { "", "", "" }; 
Random random = new Random();     

// Also you should NEVER have an endless loop ;)
while (true)         
{            
     Console.ForegroundColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));

     Console.WriteLine((x[random.Next(x.Length)]));             
     Thread.Sleep(100);         
} 

【讨论】:

  • 什么是 Console.WriteLine((x[random.Next(3)]));在代码中做什么?
  • 代码拼写错误:randonGen -> 随机
  • 用户想要输出包含在 x 数组中的随机字符串,颜色随机。 Console.WriteLine 将输出数组中包含的字符串之一,因为 random.Next(3) 将生成一个介于 0 和 2 之间的数字,这将表示所需字符串在数组中的位置。因此,是random.Next(3)返回实例0,数组中的第一个字符串将写入控制台。
  • 我想从数组中生成颜色(?),我希望它随机化,例如。 ConsoleColor.Red 或 ConsoleColor.Green。上面的代码由于某种原因不起作用,我收到颜色错误
  • Color.FromArgb 给出错误不能将 System.Drawing.Color 类型隐式转换为 System.ConsoleColor
【解决方案2】:

如果您想使用标准控制台颜色,您可以混合ConsoleColor EnumerationEnum.GetNames() 以获得随机颜色。然后您可以使用Console.ForegroundColor 和/或Console.BackgroundColor 来更改控制台的颜色。

// Store these as static variables; they will never be changing
String[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor));
int numColors = colorNames.Length;

// ...

Random rand = new Random(); // No need to create a new one for each iteration.
string[] x = new string[] { "", "", "" };
while(true) // This should probably be based on some condition, rather than 'true'
{
    // Get random ConsoleColor string
    string colorName = colorNames[rand.Next(numColors)];
    // Get ConsoleColor from string name
    ConsoleColor color = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), colorName);

    // Assuming you want to set the Foreground here, not the Background
    Console.ForegroundColor = color;

    Console.WriteLine((x[rand.Next(x.Length)]));
    Thread.Sleep(100);
}

【讨论】:

  • 我注意到上面的代码从未设置控制台颜色,它只是检索了一个随机颜色。此外,还有一些不匹配的变量名称。我已经修复了代码 sn-p。
猜你喜欢
  • 1970-01-01
  • 2023-01-05
  • 1970-01-01
  • 2010-12-07
  • 2011-06-11
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多