How to dynamically compute a list of colors?

前端 未结 3 1066
粉色の甜心
粉色の甜心 2020-12-10 18:19

In order to represent a List of Objects with different colors in a GWT-Widget, we need to get dynamically a List of colors with as much different colors as objects. Since th

3条回答
  •  無奈伤痛
    2020-12-10 19:14

    If I understand your situation correct, you're after a number of colors that look sort of "as different as possible"? I would in that case suggest that you vary the hue value (two red colors with slightly different brightness won't look much different), so you get something like a "rainbow-palette":

    This can be achieved with the following code:

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

    An example usage with a screen shots below:

    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 = 6 and numCols = 40 yields the following two screenshots:

    enter image description here enter image description here

    If you need like more than 30 colors, you could of course change the brightness and perhaps the saturation as well, and have, for instance, 10 dark colors, 10 midtone colors, and 10 bright colors.

提交回复
热议问题