Programmatically make a color more transparent

TrolliOlli picture TrolliOlli · Jun 21, 2013 · Viewed 16.9k times · Source

I'm working on a simple bar graph application that uses a static array of colors for divvying out bar colors. I would like the functionality to either draw bars normally, or slightly transparent.

Is there a way to programmatically adjust a color integer so that it's slightly transparent? Or will I have to statically define a transparent version of each color and then switch to using these versions whenever I want transparency?

Answer

Anton Ryabyh picture Anton Ryabyh · Jun 20, 2015

If you are using support library, you can use

ColorUtils.setAlphaComponent(int color, int alpha).

If you are not using support library, one-line solution taking from it's source code is:

int res = (color & 0x00ffffff) | (alpha << 24);