6

I have color in the String.xml file like this <color name="ItemColor1">#ffff992b</color> how can i convert is into four variables

float Red;
float Green;
float Blue;
float Alfa;

in Java Code? any one can help

AnasBakez
  • 1,230
  • 4
  • 20
  • 36

5 Answers5

18

You could also use the [red, green, blue] function of the Color class:

    int color = getResources().getColor(R.color.youcolor);
    int r = Color.red(color);
    int g = Color.green(color);
    int b = Color.blue(color);
Nicholas Ng
  • 1,428
  • 18
  • 23
Johann
  • 181
  • 1
  • 2
15

Edit: This was accepted as the answer but have a look at @johann's answer too, it will leave you and those reading your code less confused.

If you want to learn about the underlying representation of colours, you could start here.

Original answer:

getColor() gives you the colour as an ARGB int.

int color = getResources().getColor(R.color.ItemColor1);
float red   = (color >> 16) & 0xFF;
float green = (color >> 8)  & 0xFF;
float blue  = (color)       & 0xFF;
float alpha = (color >> 24) & 0xFF;
ahoff
  • 1,117
  • 10
  • 23
4

Please take a look

How to get RGB value from hexadecimal color code in java

int color = Integer.parseInt(myColorString, 16);
int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = (color >> 0) & 0xFF;
Community
  • 1
  • 1
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
1

Updated with ContextCompat as getColor is Deprecated.

int color = ContextCompat.getColor(mContext, R.color.colorAccent);
float red = (color >> 16) & 0xFF;
float green = (color >> 8) & 0xFF;
float blue = (color) & 0xFF;
float alpha = (color >> 24) & 0xFF;

Hope it will useful.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
0

This function converts an color value to an RGBA value. The color value can be in the form of an integer, a string, or an array. The RGBA color value is returned as an array of four floats.

public static float[] toRGBA(int color) {
    float[] rgba = new float[4];
    rgba[0] = (color >> 16) & 0xFF;
    rgba[1] = (color >> 8)  & 0xFF;
    rgba[2] = (color)       & 0xFF;
    rgba[3] = (color >> 24) & 0xFF;
    return rgba;
}
Mohamed Rahal
  • 61
  • 1
  • 3