java 将 RGBA 值转换为十六进制颜色代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10459879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert RGBA values to hex color code
提问by Kaikz
I have some sliders in my application that allows the user to change ARGB colors, however I need to convert these values to a hex value like 0xff000000, which is solid black.
我的应用程序中有一些滑块允许用户更改 ARGB 颜色,但是我需要将这些值转换为十六进制值,如 0xff000000,它是纯黑色。
This is what I have so far:
这是我到目前为止:
protected int toHex(Color col) {
String as = pad(Integer.toHexString(col.getAlpha()));
String rs = pad(Integer.toHexString(col.getRed()));
String gs = pad(Integer.toHexString(col.getGreen()));
String bs = pad(Integer.toHexString(col.getBlue()));
String hex = "0x" + as + rs + gs + bs;
return Integer.parseInt(hex, 16);
}
private static final String pad(String s) {
return (s.length() == 1) ? "0" + s : s;
}
However upon getting the Integer value like below, I get a NumberFormatException for input string: "0xccffffff":
但是,在获得如下所示的 Integer 值后,我将收到输入字符串的 NumberFormatException:“0xccffffff”:
int color = toHex(new Color(153f, 153f, 153f, 0.80f));
Any ideas on how to get this to an Integer? Thanks.
关于如何将其转换为整数的任何想法?谢谢。
采纳答案by Wezelkrozum
The Color parameters must be floats between 1f and 0f. So this is a valid color:
颜色参数必须在 1f 和 0f 之间浮动。所以这是一个有效的颜色:
int color = toHex(new Color(1f, 1f, 1f, 1f));
Which is white.
哪个是白色的。
回答by Stroboskop
The problem is that you are including alpha values.
So your maximum color code is #FFFFFFFF
(8 digits).
问题是您包含了 alpha 值。所以你的最大颜色代码是#FFFFFFFF
(8 位数字)。
The method Integer.parseInt
will let you parse value from -0x80000000
to 0x7FFFFFFF
. In order to get your value 0xCC999999
from it, you would have to negate the value and input -0x33666667
- which is of course not useful at all.
该方法Integer.parseInt
将让您从-0x80000000
to解析值0x7FFFFFFF
。为了从中获得价值0xCC999999
,您必须否定价值和输入-0x33666667
——这当然根本没有用。
The clunky but stable workaround is using Long
.
笨重但稳定的解决方法是使用Long
.
(int) Long.parseLong(text, 16)