The Android Palette API

Why you need to use the Palette API ?

Palette is a new API for Android that allows you to extract and make use of colors in an image. It also has a support library in order for older versions of Android to make use of Palette.

How to start using Palette API ?

To get started, add the Palette dependency to your build.gradle file

compile 'com.android.support:palette-v7:21.0.+'

How to work with Palette API ?

Step 1 :

Create an Object of the Palette class using Bitmap from which we need to pick the colors.

a. To Create Synchronously

public Palette generate(Bitmap image)

b. To Create Asynchronously

Palette.from( bitmap ).generate( new Palette.PaletteAsyncListener() {
@Override
public void onGenerated( Palette palette ) {
//work with the palette here
}
})


Swatch objects represent colors generated from an image's palette. Each Swatch contains:
  • an RGB (Red, Green, Blue) and HSL (Hue, Saturation, Lightness) value for a color.
  • a population value reflecting the number of pixels represented by the Swatch.
  • a color value that can be used for title text when displayed on the Swatch's primary color.
  • a color value that can be used for a body of text when displayed on the Swatch's primary color.

Each Palette has a no of Swatches that you can list using

List<Palette.Swatch> getSwatches();


Applying Palette API to CollapsibleToolbarLayout and getting values from Swatch

Palette.Swatch swatch = palette.getVibrantSwatch();
if (swatch != null) {
collapsetoolbar.setContentScrimColor(swatch.getRgb());
int population = swatch.getPopulation(); // gets population of this
swatch textView.setTextColor(swatch.getTitleTextColor()); // to set text color you can use this
}


This is one of the swatches. You can use any of the 6 most commonly obtained from the Palette :

1. getVibrantSwatch()
2. getLightVibrantSwatch()
3. getDarkVibrantSwatch()
4. getLightMutedSwatch()
5. getDarkMutedSwatch()
6. getMutedSwatch()


Accordingly you can get the above values ( RGB, TitleTextColor and more ) from the obtained Swatch. Just make sure to check

if(swatch !=null ){}

before obtaining values as not all Swatches are available for the Palette.

Check out the Complete Palette Section in the Ultimate Android Marshmallow Tutorial.

LearningKart Team