A way of getting a corresponding hex colour code g

2019-01-25 10:37发布

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?

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-25 11:17
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楼-- · 2019-01-25 11:22
String.format("#%06x", color.getRGB() & 0x00FFFFFF)

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

查看更多
欢心
4楼-- · 2019-01-25 11:23

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());
查看更多
Summer. ? 凉城
5楼-- · 2019-01-25 11:28

Read this: Getting Html color codes with a JColorChooser

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

查看更多
登录 后发表回答