5

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,220
  • 4
  • 19
  • 36

4 Answers4

16

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,368
  • 14
  • 23
Johann
  • 161
  • 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
  • 800
  • 7
  • 20
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,570
  • 3
  • 36
  • 36
0

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
  • 56,749
  • 54
  • 254
  • 407