我想为图形图表生成随机颜色,但我尝试的是无法识别的,并且生成的颜色通常彼此相似。是否可以创造这样的颜色?
我的方法:
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;
}
答案 0 :(得分:0)
这是一个RandomColors
课程,它结合了Taw和OldBoyCoder的建议。根据您想要生成的颜色数量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;
}
}