How to dynamically compute a list of colors?

前端 未结 3 1080
粉色の甜心
粉色の甜心 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 18:58

    Another version of my solution with ranges:

    List getUniqueColors(int amount) {
        final int lowerLimit = 0x10;
        final int upperLimit = 0xE0;    
        final int colorStep = (upperLimit-lowerLimit)/Math.pow(amount,1f/3);
    
        final List colors = new ArrayList(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;
    }
    

    This one is more advance as it generates the colors that differ from each other as much as possible (something like @aiiobe did).

    Generally we split the range to 3 subranges of red green and blue, calculate how many steps do we need to iterate each of them (by applying a pow(range,1f/3)) and iterate them.

    Given the number 3 for example, it will generate 0x0000B1, 0x00B100, 0x00B1B1. For number 10 it will be: 0x000076, 0x0000EC, 0x007600, 0x007676, 0x0076EC, 0x00EC00, 0x00EC76, 0x00ECEC, 0x760000, 0x760076

提交回复
热议问题