Java - toString to Colour

无人久伴 提交于 2019-12-10 22:55:59

问题


I have been trying to work this out all day.

Basically I have made a for loop which adds entries into an arraylist. One of the entries is a "Colour" varible. I have used the random.nextInt to create new values for the red, green and blue parts of the colour constructor. I have also set a toString method so I can see the values going into the arraylist.

Problem is:

When printing out I get : java.awt.Color[r=248,g=103,b=53]

and I understand why that is so, I'm just wondering how I can change that so the output says the word "orange" or "green" or "purple" depending on what the random rgb values are.

I looked on here and I found that I could possibly use the getRGB method and parsing and thats where I get stuck... any help would be great :)


回答1:


You can create a class which extends Color and has a String named "colorName", then print it on toString.

By default, Color do not store this name, also, it's hard do identify colors by comparing these Red, Green, Blue values.




回答2:


This does not exist. Good luck with rolling your own - it would need to return one of 256 x 256 x 256 (16,777,216) distinct strings to work. How would you distinguish all the shades of blue, for example? Why doesn't the RGB value work for you?




回答3:


You could subclass Color and override the toString method (or create a printColour method or whatever name) and then you could output a certain colour label for a certain range of RGB values.

Obviously your choice of the colour names and the specific range you assign them will be completely subjective.




回答4:


You can subclass Color to either override the toString() method or add another method of your own to covert the RGB to a named color. Or you could have a static method somewhere that converts RGB to a named color.

However given there are 256 * 256 * 256 =~ 16 million different RGB combinations most of your random RGB combinations will not correspond to a named color. So not sure it's worth doing.




回答5:


This is non-trivial and rather subjective.

However, you might want to look at http://blog.xkcd.com/2010/05/03/color-survey-results/ which attempts to answer this.




回答6:


I've never really came across something you're asking for, but would this work for you? (You might need to add more colors for your needs) :

public final class ColorUtil {

    static private HashMap<String,Color> KNOWNCOLORS = new HashMap<String,Color>();

    static {
        KNOWNCOLORS.put("black",     Color.black);
        KNOWNCOLORS.put("darkgray",  Color.darkGray);
        KNOWNCOLORS.put("lightgray", Color.lightGray);
        KNOWNCOLORS.put("white",     Color.white);
        KNOWNCOLORS.put("red",       Color.red);
        KNOWNCOLORS.put("blue",      Color.blue);
        KNOWNCOLORS.put("green",     Color.green);
        KNOWNCOLORS.put("pink",      Color.pink);
        KNOWNCOLORS.put("cyan",      Color.cyan);
        KNOWNCOLORS.put("purple",    Color.magenta);
        KNOWNCOLORS.put("orange",    Color.orange);
        KNOWNCOLORS.put("yellow",    Color.yellow);
        // add more here
    }


    static public String getBestColorName(Color c) {
        int dist, diff = Integer.MAX_VALUE;
        String colorName = toHex(c);
        Color c2;

        for (String name : KNOWNCOLORS.keySet()) {
            c2 = KNOWNCOLORS.get(name);
            dist = Math.abs(c.getRed() - c2.getRed())
                    + Math.abs(c.getGreen() - c2.getGreen()) 
                    + Math.abs(c.getBlue() - c2.getBlue())
                    + Math.abs(c.getAlpha() - c2.getAlpha());

            if (dist < diff) {
                diff = dist;
                colorName = name; 
            }
        }

        return colorName;
    }

    static public int getColorValue(Color c) {
        return (c.getAlpha() << 24) 
            | (c.getRed() << 16)
            | (c.getGreen() << 8) 
            | (c.getBlue()); 
    }

    static public String toHex(Color c) {
        StringBuilder b = new StringBuilder();
        if (c.getAlpha() < 255) {
            b.append(padLeft(Integer.toString(c.getAlpha(), 16), 2));
        }
        b.append(padLeft(Integer.toString(c.getRed(), 16), 2));
        b.append(padLeft(Integer.toString(c.getGreen(), 16), 2));
        b.append(padLeft(Integer.toString(c.getBlue(), 16), 2));

        return b.toString();
    }

    static private String padLeft(String s, int n) {
        return String.format("%1$#" + n + "s", s).replace(" ", "0");
    }

    private ColorUtil() {}



    static public void main(String...args) {
        Color c;

        for (String name : KNOWNCOLORS.keySet()) {
            if (!name.equals(getBestColorName(KNOWNCOLORS.get(name)))) {
                System.out.println("*** ERR!! Could not match color " + name);
            } 
        }

        for (int i=0; i<30; i++) {
            c = new Color((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256));

            System.out.println("Color " + toHex(c) 
                 + " (" + c.getAlpha() + "," + c.getRed() + "," + c.getGreen() + "," + c.getBlue() + ")"
                 + " = " + getBestColorName(c));
        }

        System.out.println("Done!");
    }

}

Sample output :

Color e75848 (255,231,88,72) = red
Color 6f4854 (255,111,72,84) = darkgray
Color 5dc6af (255,93,198,175) = lightgray
Color 190971 (255,25,9,113) = darkgray
Color 8ef300 (255,142,243,0) = yellow
Color c2ec5b (255,194,236,91) = lightgray
Color 998794 (255,153,135,148) = lightgray
Color 328d06 (255,50,141,6) = darkgray
Color 223d03 (255,34,61,3) = darkgray
Color 51dfea (255,81,223,234) = cyan
Color baa801 (255,186,168,1) = orange
Color 8370d4 (255,131,112,212) = lightgray
Color 7766bd (255,119,102,189) = lightgray
Color 35024b (255,53,2,75) = darkgray
Color cdbfad (255,205,191,173) = lightgray
Color 5e3a21 (255,94,58,33) = darkgray
Color 11af5d (255,17,175,93) = darkgray
Color 480995 (255,72,9,149) = darkgray
Color 04adab (255,4,173,171) = cyan
Color 98641c (255,152,100,28) = darkgray
Color 3ef68c (255,62,246,140) = cyan
Color 4d091a (255,77,9,26) = darkgray
Color 56117d (255,86,17,125) = darkgray
Color 1a00ea (255,26,0,234) = blue
Color 2ffd3e (255,47,253,62) = green
Color 9a918b (255,154,145,139) = lightgray
Color 6f8f0e (255,111,143,14) = darkgray
Color 5f3e25 (255,95,62,37) = darkgray
Color 914e79 (255,145,78,121) = darkgray
Color 57f88b (255,87,248,139) = cyan
Done!


来源:https://stackoverflow.com/questions/5708830/java-tostring-to-colour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!