从RGBA到Hex

时间:2013-07-25 08:45:12

标签: java android

我正在尝试将RGBA值(4个值分割)转换为HEX值。

目前,我已经有了这段代码:

int red = Integer.parseInt(colors[0]);
int green = Integer.parseInt(colors[1]);
int blue = Integer.parseInt(colors[2]);
float alpha = Float.parseFloat(colors[3]);

所以现在,我希望将这些颜色变为HEX,因此我可以使用此方法创建颜色:new ColorDrawable(0xFF99CC00)

任何提示?

4 个答案:

答案 0 :(得分:2)

public int toHex(Color color) {
    String alpha = pad(Integer.toHexString(color.getAlpha()));
    String red = pad(Integer.toHexString(color.getRed()));
    String green = pad(Integer.toHexString(color.getGreen()));
    String blue = pad(Integer.toHexString(color.getBlue()));
    String hex = "0x" + alpha + red + green + blue;
    return Integer.parseInt(hex, 16);
}

private static final String pad(String s) {
    return (s.length() == 1) ? "0" + s : s;
}

<强>用法

int color = toHex(new Color(1f, 1f, 1f, 1f));

或者您可以使用

Color.argb(a_int, r_int, g_int, b_int);
//(Multiply int value by 255.0f)

答案 1 :(得分:1)

找到它:

ActionBar bar = this.getActionBar();
String hex = String.format("#%02x%02x%02x%02x", alpha,red, green, blue);
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(hex)));

答案 2 :(得分:0)

将 rgba 转换为 Hexa 颜色: 您可以使用此功能, rgba 值例如:rgba(255,249,249,0.54)

fun rgbaToHexa(color: String): String? {
    try {
        val value = color.removePrefix("rgba(").removeSuffix(")").split(",")
        val red = value[0].toInt()
        val green = value[1].toInt()
        val blue = value[2].toInt()

        val hex = String.format("#%02x%02x%02x", red, green, blue)

        return hex
    } catch (e: Exception) {
        loge("exception:${e.printStackTrace()}")
    }

    return null
}

答案 3 :(得分:-1)

相关问题