How to randomly receive a Material Design Color?

前端 未结 5 1252
南笙
南笙 2021-02-01 15:38

Google has their Color - Guidelines, so how to randomly receive a color? Is there a way to specify a number from the table and receive a random color out of all colors of the ta

5条回答
  •  走了就别回头了
    2021-02-01 15:52

    Using reflection you can retrieve all java.awt.Color constants, some 148 colors with names

    for (Field field : Color.class.getDeclaredFields()) {
        int modifiers = field.getModifiers();
        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
                && Modifier.isFinal(modifiers) && field.getType() == Color.class) {
            String colorName = field.getName().toLowerCase(Locale.US);
            Color color = Color.valueOf(colorName);
            System.out.printf("- %s -> %s%n", colorName, color);
        }
    }
    

    This uses reflection, and assumes that the constant name is a human readable name.

    [139] thistle -> 0xd8bfd8ff
    [140] tomato -> 0xff6347ff
    [141] turquoise -> 0x40e0d0ff
    [142] violet -> 0xee82eeff
    [143] wheat -> 0xf5deb3ff
    [144] white -> 0xffffffff
    [145] whitesmoke -> 0xf5f5f5ff
    [146] yellow -> 0xffff00ff
    [147] yellowgreen -> 0x9acd32ff
    

    So add the colors in a list, and randomly pick one with random.nextInt(colors.size()).

提交回复
热议问题