您知道任何生成随机颜色的方法(不是随机颜色名称!)?
我已经有一个,但是这个正确地做到了:
这只返回绿色:
Random r = new Random();
BackColor = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), 0);
这只返回红色:
Random r = new Random();
BackColor = Color.FromArgb(r.Next(0, 256), 0, 0);
这只返回Blue:
Random r = new Random();
BackColor = Color.FromArgb(0, 0, r.Next(0, 256));
我希望我的代码每次都返回一个随机颜色,不仅是绿色/红色/蓝色,如上所述。
如何解决这个问题?
任何建议都会得到快乐的批准!
答案 0 :(得分:21)
以下是我在您删除并删除问题之前开始发布的答案:
public partial class Form1 : Form
{
private Random rnd = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
BackColor = randomColor;
}
}
答案 1 :(得分:6)
您上一个方法的原始版本(预编辑)将返回所有不同种类的颜色。我肯定会使用一个Random对象,而不是每次都创建一个新对象:
Random r = new Random();
private void button6_Click(object sender, EventArgs e)
{
pictureBox1.BackColor = Color.FromArgb(r.Next(0, 256),
r.Next(0, 256), r.Next(0, 256));
Console.WriteLine(pictureBox1.BackColor.ToString());
}
它产生各种不同的颜色:
颜色[A = 255,R = 241,G = 10,B = 200]
颜色[A = 255,R = 41,G = 125,B = 132]
颜色[A = 255,R = 221,G = 169,B = 109]
颜色[A = 255,R = 228,G = 152,B = 197]
颜色[A = 255,R = 50,G = 153,B = 103]
颜色[A = 255,R = 92,G = 236,B = 162]
颜色[A = 255,R = 52,G = 103,B = 204]
颜色[A = 255,R = 197,G = 126,B = 133]