Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert colors from Hex to RGB

Tags:

android

colors

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

like image 476
AnasBakez Avatar asked May 15 '12 11:05

AnasBakez


People also ask

Are hex colors the same as RGB?

There is no informational difference between RGB and HEX colors; they are simply different ways of communicating the same thing – a red, green, and blue color value. HEX, along with its sister RGB, is one of the color languages used in coding, such as CSS. HEX is a numeric character based reference of RGB numbers.


3 Answers

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);
like image 187
Johann Avatar answered Nov 03 '22 22:11

Johann


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;
like image 28
ahoff Avatar answered Nov 03 '22 23:11

ahoff


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;
like image 34
Dheeresh Singh Avatar answered Nov 03 '22 23:11

Dheeresh Singh