将整数颜色值转换为RGB

时间:2013-06-19 05:38:29

标签: java android colors type-conversion

我正在尝试修改第三方软件。我想使用一些方法(我不能修改)返回的颜色作为整数。但是,我想使用RGB格式,如#FF00FF。如何进行转换?

这是一个HTML示例http://www.shodor.org/stella2java/rgbint.html 我想在Android上用Java存档相同的东西。

4 个答案:

答案 0 :(得分:63)

我发现对我来说最简单和最好的解决方案是直接使用Color类,如下所示:

int red = Color.red(intColor);
int green = Color.green(intColor);
int blue = Color.blue(intColor);
int alpha = Color.alpha(intColor);

这样我就可以处理整数值而无需处理字符串。另一方面,如果代表rgb颜色的字符串是你需要的,Pankaj Kumar的答案是最好的。我希望这对某人有用。

答案 1 :(得分:39)

使用此

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

我们知道HEX中的颜色值长度为6.所以你在这里看到6。 %06X匹配来自(0xFFFFFF& intColor)的结果,如果length小于6,则通过将ZERO附加到结果的左侧来使结果为6。你看到#,所以这个#char被附加到结果,最后你得到一个HEX COLOR值。


  

自API 26起更新

自API 26以来,为了类似的原因,引入了新方法Color.valueOf(....)来转换颜色。你可以像

一样使用它
// 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());

答案 2 :(得分:1)

RGB使用六进制数字格式。 如果你有整数值,将它转换为hexa,。

答案 3 :(得分:1)

Since SDK 26 you can just use

Color c = Color.valueOf(colorInt);

apart from that it does not seem to possible to create a Color instance from arbitrary argb. The underlying code uses a private constructor:

/**
 * Creates a new <code>Color</code> instance from an ARGB color int.
 * The resulting color is in the {@link ColorSpace.Named#SRGB sRGB}
 * color space.
 *
 * @param color The ARGB color int to create a <code>Color</code> from
 * @return A non-null instance of {@link Color}
 */
@NonNull
public static Color valueOf(@ColorInt int color) {
    float r = ((color >> 16) & 0xff) / 255.0f;
    float g = ((color >>  8) & 0xff) / 255.0f;
    float b = ((color      ) & 0xff) / 255.0f;
    float a = ((color >> 24) & 0xff) / 255.0f;
    return new Color(r, g, b, a, ColorSpace.get(ColorSpace.Named.SRGB));
}