Marwan Zakariya
Marwan Zakariya

Reputation: 489

convert from hex color to RGB

How can I get RGB values from color in form "#6F00AC"?

I tried this but didn't worked

int newcolor = (int)Long.parseLong(String.valueOf(Color.parseColor("#6F00AC")), 16);
    float r = ((newcolor >> 16) & 0xFF) / 255f;
    float g = ((newcolor >> 8) & 0xFF) / 255f;
    float b = ((newcolor >> 0) & 0xFF) / 255f;

Upvotes: 2

Views: 2598

Answers (1)

Blackbelt
Blackbelt

Reputation: 157487

Color has the static methods red/blue/green and alpha

int color = Color.parseColor("#6F00AC");
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);

they return respectively the red, blue, green, alpha component of a color int.

EDIT:

Your code is almost correct, (you don't need to divide by 255)

int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = color & 0xFF;

Upvotes: 4

Related Questions