我写了下面的两个方法来自动选择N个不同的颜色。它的工作原理是在RGB立方体上定义一个分段线性函数。这样做的好处是,如果这是你想要的,你也可以得到一个渐进式的比例,但是当N变大时,颜色看起来会变得相似。我还可以想象将RGB立方体均匀地细分为一个晶格,然后绘制点。还有人知道其他方法吗?我排除了定义一个列表然后循环浏览它的可能性。我还应该说,我通常不关心它们是否冲突或看起来不好看,它们只需要在视觉上清晰即可。
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);
}
发布于 2021-07-17 03:57:14
上面有很多非常好的答案,但如果有人正在寻找快速的python解决方案,那么提到python包distinctify可能会很有用。这是一个可从pypi获得的轻量级包,使用起来非常简单:
from distinctipy import distinctipy
colors = distinctipy.get_colors(12)
print(colors)
# display the colours
distinctipy.color_swatch(colors)
它返回rgb元组的列表
[(0, 1, 0), (1, 0, 1), (0, 0.5, 1), (1, 0.5, 0), (0.5, 0.75, 0.5), (0.4552518132842178, 0.12660764790179446, 0.5467915225460569), (1, 0, 0), (0.12076092516775849, 0.9942188027771208, 0.9239958090462229), (0.254747094970068, 0.4768020779917903, 0.02444859177890535), (0.7854526395841417, 0.48630704929211144, 0.9902480906347156), (0, 0, 1), (1, 1, 0)]
此外,它还具有一些附加的不错的功能,例如生成与现有颜色列表不同的颜色。
https://stackoverflow.com/questions/470690
复制相似问题