A way of getting a corresponding hex colour code given a Color object in Java?

前端 未结 4 1485
北荒
北荒 2020-12-17 22:57

I\'ve inspected the Java class documentation for Color and found that I can generate a Color object from a hex code string (e.g. \"#FFFFFF\") using the Co

相关标签:
4条回答
  • 2020-12-17 23:08
    String.format("#%06x", color.getRGB() & 0x00FFFFFF)
    

    The masking is used for removing the alpha component, in bits 24-31

    0 讨论(0)
  • 2020-12-17 23:18
    Color color = Color.BLUE;
    Formatter f = new Formatter(new StringBuffer("#"));
    f.format("%02X", color.getRed());
    f.format("%02X", color.getGreen());
    f.format("%02X", color.getBlue());
    f.toString(); //#0000FF
    
    0 讨论(0)
  • 2020-12-17 23:24

    There is another way. Thought I just add this alternative.

    // ARGB = (255, 255, 0, 0) (Red) 
    // hex -> "ffff0000"
    String hex = Integer.toHexString(color.getRGB());
    
    // Reduced to RGB: hex -> "#ff0000"
    hex = "#" + hex.substring(2, hex.length());
    
    0 讨论(0)
  • 2020-12-17 23:31

    Read this: Getting Html color codes with a JColorChooser

    The answer has a method to convert a color to it's hex value.

    0 讨论(0)
提交回复
热议问题