'Programmatically make a color more transparent

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?



Solution 1:[1]

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 taken from it's source code is:

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

Solution 2:[2]

Hi there you could use the:

android.support.v4.graphics.ColorUtils#setAlphaComponent

note: the alpha here is from 0 to 255 and not % based.

There are also other util methods such contract and luminosity calculations in there.

Regards

Solution 3:[3]

Try following code

int color = (int)Long.parseLong(your_color, 16);
int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = (color >> 0) & 0xFF;

if color code has alpha then

int alpha= (color >> 24) & 0xFF;

Solution 4:[4]

From the top answer I created a method to do this:

private Android.Graphics.Color AddTransparencyToColour(Android.Graphics.Color color, int transparancy)
{
    return Android.Graphics.Color.Argb(transparancy, color.R, color.G, color.B);
}

It's also worth noteing that this can be changed to an extension method like so

public static ColorExtensions
{
    public static Android.Graphics.Color AddTransparency(this Android.Graphics.Color color, int transparancy)
    {
        return Android.Graphics.Color.Argb(transparancy, color.R, color.G, color.B);
    }
}

In regards to the alpha value, from MSDN Color.FromArgb:

Remarks

To create an opaque color, set alpha to 255. To create a semitransparent color, set alpha to any value from 1 through 254.

Solution 5:[5]

I use extension functions.

fun Int.withAlpha(@IntRange(from = 0, to = 255) alpha: Int): Int {
    return (alpha shl 24) or (this and 0xFFFFFF)
}

Also possible with ColorUtils

ColorUtils.setAlphaComponent(color, alpha)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashu
Solution 2 Joao Gavazzi
Solution 3 Chintan Rathod
Solution 4
Solution 5