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