如何动态计算颜色列表?

时间:2010-08-04 08:31:52

标签: java gwt colors

为了在GWT-Widget中表示具有不同颜色的对象列表,我们需要动态获得具有与对象不同颜色的颜色列表。由于List的大小可能不同,我们需要能够计算这样的颜色列表。

3 个答案:

答案 0 :(得分:7)

我的解决方案的另一个版本,其中包含范围:

List<int> getUniqueColors(int amount) {
    final int lowerLimit = 0x10;
    final int upperLimit = 0xE0;    
    final int colorStep = (upperLimit-lowerLimit)/Math.pow(amount,1f/3);

    final List<int> colors = new ArrayList<int>(amount);

    for (int R = lowerLimit;R < upperLimit; R+=colorStep)
        for (int G = lowerLimit;G < upperLimit; G+=colorStep)
            for (int B = lowerLimit;B < upperLimit; B+=colorStep) {
                if (colors.size() >= amount) { //The calculated step is not very precise, so this safeguard is appropriate
                    return colors;
                } else {
                    int color = (R<<16)+(G<<8)+(B);
                    colors.add(color);
                }               
            }
    return colors;
}

这个更加先进,因为它产生的颜色尽可能彼此不同(像@aiiobe那样)。

通常我们将范围分为红色绿色和蓝色的3个子范围,计算我们需要迭代每个步骤的步数(通过应用pow(范围,1f / 3))并迭代它们。

例如,给定数字3,它将生成0x0000B1, 0x00B100, 0x00B1B1。对于数字10,它将是:0x000076, 0x0000EC, 0x007600, 0x007676, 0x0076EC, 0x00EC00, 0x00EC76, 0x00ECEC, 0x760000, 0x760076

答案 1 :(得分:6)

我想这样的事情。没有随机性,只计算要采取的颜色步骤,并将所有颜色范围分割为该步骤。如果限制下限 - 您将删除太深的颜色,限制上限将删除太亮的颜色。

List<Integer> getUniqueColors(int amount) {
    final int lowerLimit = 0x101010;
    final int upperLimit = 0xE0E0E0;
    final int colorStep = (upperLimit-lowerLimit)/amount;

    final List<Integer> colors = new ArrayList<Integer>(amount);
    for (int i=0;i<amount;i++) {
        int color = lowerLimit+colorStep*i;
        colors.add(color);
    }
    return colors;
}

答案 2 :(得分:5)

如果我理解你的情况是正确的,你会看到一些看起来“尽可能不同”的颜色?在这种情况下我会建议你改变色调值(亮度略有不同的两种红色看起来不会有太大不同),所以你会得到类似“彩虹色调”的东西:

这可以通过以下代码实现:

Color[] cols = new Color[n];
for (int i = 0; i < n; i++)
    cols[i] = Color.getHSBColor((float) i / n, 1, 1);

以下屏幕截图的示例用法:

import java.awt.*;

public class TestComponent extends JPanel {

    int numCols = 6;

    public void paint(Graphics g) {

        float h = 0, dh = (float) getHeight() / numCols;
        Color[] cols = getDifferentColors(numCols);

        for (int i = 0; i < numCols; i++) {
            g.setColor(cols[i]);
            g.fillRect(0, (int) h, getWidth(), (int) (h += dh));
        }
    }

    public static Color[] getDifferentColors(int n) {
        Color[] cols = new Color[n];
        for (int i = 0; i < n; i++)
            cols[i] = Color.getHSBColor((float) i / n, 1, 1);
        return cols;
    }

    public static void main(String s[]) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new TestComponent());
        f.setSize(200, 200);
        f.setVisible(true);
    }
}

numCols = 6numCols = 40会生成以下两个屏幕截图:

enter image description here enter image description here

如果您需要超过30种颜色,您当然可以改变亮度和饱和度,例如,有10种深色,10种中间色和10种鲜艳色。