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

戏子无情 提交于 2019-11-28 00:03:51

问题


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 Color.decode(); method.

I would like to implement the reverse process for a project I am working on, but there doesn't seem to be a method already built in to the class for this.

Is there an easy way to do this?


回答1:


String.format("#%06x", color.getRGB() & 0x00FFFFFF)

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




回答2:


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



回答3:


Read this: Getting Html color codes with a JColorChooser

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




回答4:


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());


来源:https://stackoverflow.com/questions/15113918/a-way-of-getting-a-corresponding-hex-colour-code-given-a-color-object-in-java

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