Passing argb array to int or long

673 Views Asked by At

I have a method that gives me an array with the ARGB parts of the color I need to paint into a canvas gradient. But as far as I know this gradient only accepts hexadecimal number representing colors. So I did a function based on the info I found here.

This is the function:

public static long getIntegerHexFromARGB(int a, int r, int g, int b){
    String hex = String.format("#%02x%02x%02x%02x", a, r, g, b);
    return Long.parseLong(hex,16);
}

And this is how I call it:

long rgba_outter_circle = FormulaHelpers.getIntegerHexFromARGB(argbCircleColor[0], argbCircleColor[1], argbCircleColor[2], argbCircleColor[3]);

My problem is that this code is inside a custom view I´m doing for including it inside a layout, and the Android Studio layout editor claims about this:

java.lang.NumberFormatException: For input string: "#64FF0000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:430)
at java.lang.Long.valueOf(Long.java:513)
at math.FormulaHelpers.getIntegerHexFromARGB(FormulaHelpers.java:41)
at framework.joystickController.JoystickButtonView.onMeasure(JoystickButtonView.java:177)
at android.view.View.measure(View.java:17430)
... and much more

The line it claims is FormulaHelpers:41, that is:

return Long.parseLong(hex,16);

Can somebody see what I´m doing wrong? I can't find the problem anywhere Sorry for my english

3

There are 3 best solutions below

0
On BEST ANSWER

Correct hex number in Java starts with '0x', not with '#'. Your number should be "0x64FF0000", and the format should be "0x%02x%02x%02x%02x". You can also create an int using formula:

int color = (a<<24) | (r<<16) | (g<<8) | b

This method should work as well:

Color.argb(a,r,g,b)
0
On

If you want it to be parsable to Long format, remove # from your hex string: IE

String hex = String.format("%02x%02x%02x%02x", a, r, g, b);
0
On

It looks like you want to use this method from Color:

public static int parseColor (String colorString)

I think it will do exactly what you want.

It will work on strings with the format you use right now, but also take color names.