问题描述
我正在尝试修改第三方软件.我想使用由某些方法(我无法修改)返回的颜色作为整数.但是,我想使用 RGB 格式,例如#FF00FF.如何进行转换?
I am trying to modify a third party software. I want to use a color which is returned by some methods (which I cant modifiy) as an integer. However, I would like to use RGB format, like #FF00FF. How can I make a conversion?
这是一个 HTML 示例 http://www.shodor.org/stella2java/rgbint.html我想在 Android 上用 Java 归档相同的内容.
Here is an HTML example http://www.shodor.org/stella2java/rgbint.htmlI would like to archive same thing in Java, on Android.
推荐答案
使用这个
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
我们知道 HEX 中颜色值的长度是 6.所以你在这里看到 6.%06X 匹配来自 (0xFFFFFF & intColor) 的结果,如果长度小于 6,则通过在结果的左侧附加零来使结果为 6.你会看到 #,所以这个 # 字符被附加到结果中,最后你会得到一个十六进制颜色值.
We know lenght of color value in HEX is 6. So you see 6 here. %06X matches the result coming from (0xFFFFFF & intColor) and if length is less than 6, it makes result with 6 by appending ZERO to left side of result. And you see #, so this # char gets appended to result and finally you get a HEX COLOR value.
自 API 26 起更新
自 API 26 起,新方法 Color.valueOf(....)
出于类似的原因被引入来转换颜色.你可以像
Since API 26, new methods Color.valueOf(....)
has been introduced to convert colors for similar reason. you can use it like
// sRGB
Color opaqueRed = Color.valueOf(0xffff0000); // from a color int
Color translucentRed = Color.valueOf(1.0f, 0.0f, 0.0f, 0.5f);
// Wide gamut color
ColorSpace sRgb = ColorSpace.get(ColorSpace.Named.SRGB);
@ColorLong long p3 = Color.pack(1.0f, 1.0f, 0.0f, 1.0f, sRgb);
Color opaqueYellow = Color.valueOf(p3); // from a color long
// CIE L*a*b* color space
ColorSpace lab = ColorSpace.get(Named.CIE_LAB);
Color green = Color.valueOf(100.0f, -128.0f, 128.0f, 1.0f, lab);
mView.setBackgroundColor(opaqueRed.toArgb());
mView2.setBackgroundColor(green.toArgb());
mView3.setBackgroundColor(translucentRed.toArgb());
mView4.setBackgroundColor(opaqueYellow.toArgb());
这篇关于将整数颜色值转换为 RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!