Palette Library: How to add transparency to Palette Swatch Color?

1.2k Views Asked by At

How can I add transparency value to a palette's swatch? Like I am adding the color(swatch.getRGB()) to a linear layout, It shows solid color. And I don't want to use alpha as it will make other items in layout transparent too.

My code snippet:

Palette palette = Palette.from(myBitmap).generate();
Palette.Swatch swatch1 = palette.getDarkVibrantSwatch();
int color = swatch1.getRgb();
thatLayout.setBackgroundColor(color)
3

There are 3 best solutions below

0
On

I haven't tested this but something like this should work

private int setAlpha(int color, int alpha) {
  alpha = (alpha << 24) & 0xFF000000;
  return alpha | color;
}
1
On

This is how i got the transparent RGB integer value

Bitmap myDisplayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_pic);
if (myDisplayBitmap != null && !myDisplayBitmap.isRecycled())
{
    Palette palette = Palette.from(myDisplayBitmap).generate();
    Palette.Swatch vibrantSwatch = palette.getDarkVibrantSwatch();

    /*If vibrantSwatch is null then return 0 otherwise :-) */
    int opaqueDarkVibrantColor = vibrantSwatch != null ? vibrantSwatch.getRgb() : 0;

     /*Call the method that returns alpha color */
    int transparentRGBInt = getColorWithAplha(opaqueDarkVibrantColor, 0.5f)
    yourLayout.setBackgroundColor(transparentRGBInt);

    // prints something like -2146428888
    Log.i("info", String.valueOf(transparentRGBInt)); 

}

and here is the method that returns alpha value, you need to pass two params int RGB color value and ratio of transparency.

/**
     * @param color opaque RGB integer color for ex: -11517920
     * @param ratio ratio of transparency for ex: 0.5f
     * @return transparent RGB integer color
     */
    private int getColorWithAplha(int color, float ratio)
    {
        int transColor = 0;
        int alpha = Math.round(Color.alpha(color) * ratio);
        int r = Color.red(color);
        int g = Color.green(color);
        int b = Color.blue(color);
        transColor = Color.argb(alpha, r, g, b);
        return transColor ;
    }

Edit

Use this to get the Hex value from the int RGB value

String opHexColor = String.format("#%06X", (0xFFFFFF & opaqueDarkVibrantColor));
0
On

Use android support utility class:

thatLayout.setBackgroundColor(ColorUtils.setAlphaComponent(swatch.getRgb(), alpha));