如何随机生成容易识别的颜色?
问题描述:
我想为图形图表生成随机颜色,但我所尝试的不可识别,并且生成的颜色通常是彼此相似的。是否有可能创造这样的颜色?如何随机生成容易识别的颜色?
我的方法:
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;
}
答
这里是一个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://*.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://*.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;
}
}
在这种情况下,你最好不要使用随机的,而是某种模式 – Ian
的见[这里](http://*.com/questions/27374550/how-to-compare-color-object以获得最接近的颜色/ 27375621?s = 1 | 1.0441#27375621)讨论颜色距离。另请查看['KnownColors'](https://msdn.microsoft.com/en-us/library/system.drawing.knowncolor(v = vs.110).aspx)! – TaW
这里有一些想法http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/和这里 http://*.com/questions/43044/algorithm-随机产生一种美观的调色板 – OldBoyCoder