Reinherd
Reinherd

Reputation: 5506

From RGBA to Hex

I'm trying to convert a RGBA value (4 values split) to a HEX value.

At the moment, I've this code:

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

So now, I want to get those colors to HEX, so I can use this method to create a Color: new ColorDrawable(0xFF99CC00)

Any tips?

Upvotes: 0

Views: 11489

Answers (4)

rNkL
rNkL

Reputation: 472

To Convert rgba to Hexa color: This function you can use, rgba value is for example : 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
}

Upvotes: 0

Reinherd
Reinherd

Reputation: 5506

Found it out:

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

Upvotes: 2

Bishan
Bishan

Reputation: 15710

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;
}

Usage

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

or you can use

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

Upvotes: 2

Related Questions