2

For a given TextView, how to get the Alpha, Red, Green and Blue values (0-255)?

I know how to set TextView.SetBackgroundColor(Color.argb(a_int, r_int, g_int, b_int));

But how to get?

Thanks a lot

nomongo
  • 3,435
  • 7
  • 30
  • 33

1 Answers1

9

Use ColorDrawable:

ColorDrawable cd = (ColorDrawable) textView.getBackground();
int color = cd.getColor();
int alpha = cd.getAlpha();
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);

Official Color Docs

The Color class defines methods for creating and converting color ints.

Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue.

The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components.

The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue.

Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution.

Thus opaque-black would be 0xFF000000 (100% opaque but no contributions from red, green, or blue), and opaque-white would be 0xFFFFFFFF

Reference

Community
  • 1
  • 1
crocboy
  • 2,887
  • 2
  • 22
  • 25
  • How do I get the R G and B values from 'color' which is an integer? – nomongo Jul 24 '14 at 19:47
  • 1
    Thanks, this is used by this post http://stackoverflow.com/questions/38426573/how-to-transform-hex-color-into-float-0-1/38426718#answer-38426718 – e-info128 Jul 19 '16 at 02:19