问题描述
我写了下面两个方法来自动选择N个不同的颜色.它的工作原理是在 RGB 立方体上定义分段线性函数.这样做的好处是,如果您想要的话,您还可以获得渐进式比例,但是当 N 变大时,颜色可能会开始看起来相似.我还可以想象将RGB立方体均匀地细分为一个点阵,然后绘制点.有谁知道其他方法吗?我排除了定义一个列表然后循环遍历它的可能性.我还应该说,我通常不在乎它们是否发生冲突或不好看,它们只需要在视觉上与众不同.
I wrote the two methods below to automatically select N distinct colors. It works by defining a piecewise linear function on the RGB cube. The benefit of this is you can also get a progressive scale if that's what you want, but when N gets large the colors can start to look similar. I can also imagine evenly subdividing the RGB cube into a lattice and then drawing points. Does anyone know any other methods? I'm ruling out defining a list and then just cycling through it. I should also say I don't generally care if they clash or don't look nice, they just have to be visually distinct.
public static List<Color> pick(int num) {
List<Color> colors = new ArrayList<Color>();
if (num < 2)
return colors;
float dx = 1.0f / (float) (num - 1);
for (int i = 0; i < num; i++) {
colors.add(get(i * dx));
}
return colors;
}
public static Color get(float x) {
float r = 0.0f;
float g = 0.0f;
float b = 1.0f;
if (x >= 0.0f && x < 0.2f) {
x = x / 0.2f;
r = 0.0f;
g = x;
b = 1.0f;
} else if (x >= 0.2f && x < 0.4f) {
x = (x - 0.2f) / 0.2f;
r = 0.0f;
g = 1.0f;
b = 1.0f - x;
} else if (x >= 0.4f && x < 0.6f) {
x = (x - 0.4f) / 0.2f;
r = x;
g = 1.0f;
b = 0.0f;
} else if (x >= 0.6f && x < 0.8f) {
x = (x - 0.6f) / 0.2f;
r = 1.0f;
g = 1.0f - x;
b = 0.0f;
} else if (x >= 0.8f && x <= 1.0f) {
x = (x - 0.8f) / 0.2f;
r = 1.0f;
g = 0.0f;
b = x;
}
return new Color(r, g, b);
}
推荐答案
您可以使用 HSL 颜色模型 来创建你的颜色.
You can use the HSL color model to create your colors.
如果您只想要不同的色调(可能),以及亮度或饱和度的细微变化,您可以像这样分配色调:
If all you want is differing hues (likely), and slight variations on lightness or saturation, you can distribute the hues like so:
// assumes hue [0, 360), saturation [0, 100), lightness [0, 100)
for(i = 0; i < 360; i += 360 / num_colors) {
HSLColor c;
c.hue = i;
c.saturation = 90 + randf() * 10;
c.lightness = 50 + randf() * 10;
addColor(c);
}
这篇关于如何自动生成N个“distinct"颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!