我想要随机生成一种颜色,要返回Color类型
颜色是有R、B、G三种数值标示的,这三个数值范围是0~255,你只需要产生这三种数据的随机数即可,然后用Color.FromArgb 函数生成颜色
using System;
using System.Drawing;
class Test
{
static void Main()
{
for (int i = 0; i <= 100; i++)
{
Color co = GetColor();
Console.WriteLine(co.Name);
}
Console.ReadKey();
}
static Color GetColor()
{
Random random = new Random();
int number = random.Next(1,4);
switch (number)
{
case 1:
return Color.Red;
case 2:
return Color.Black;
default:
return Color.Yellow;
}
}
}
public string GetRandomColor()
{
Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
// 对于C#的随机数,没什么好说的
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
// 为了在白色背景上显示,尽量生成深色
int int_Red = RandomNum_First.Next(256);
int int_Green = RandomNum_Sencond.Next(256);
int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue).Name;
}
只需生成0-255的随机整数就可以了,RGB(255,255,255)
对于HTML,#FFFFFF这种颜色,你生成单个的随机16进制数,把他们拼接在一起也行。
Color.FromArgb(random.Next(255),random.Next(255),random.Next(255))