Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active February 9, 2017 17:02
Show Gist options
  • Save pokk/e9b1b9a5c2acbfb7c3bc1f619d3f21aa to your computer and use it in GitHub Desktop.
Save pokk/e9b1b9a5c2acbfb7c3bc1f619d3f21aa to your computer and use it in GitHub Desktop.
How to use the Palette.

Introduction

We can extract the colors from the bitmap.

Start

Add the library in your app gradle.

compile 'com.android.support:palette-v7:25.1.0'

We have four ways to create the palette.

// Now Palette.from(bitmap) is the same as Palette.Builder(bitmap).

// Synchronous methods.
// --------------------------------
// These should be used when you have access to the underlying image loading thread.
// Picasso allows this through a Transformation. For other libraries, YMMV.
// Uses the default palette size (16).
Palette p = Palette.from(bitmap).generate();
// Allows you to specify the maximum palette size, in this case 24.
Palette p = Palette.from(bitmap).maximumColorCount(24).generate();

// Asynchronous methods
// --------------------------------
// This is the quick and easy integration path. Internally uses an AsyncTask so
// this may not be optimal (since you're dipping in and out of threads)
// Uses the default palette size (16).
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
    @Override
    public void onGenerated(Palette palette) {
       // Here's your generated palette
    }
});
// Allows you to specify the maximum palette size, in this case 24.
Palette.from(bitmap).maximumColorCount(24).generate(new Palette.PaletteAsyncListener() {
    @Override
    public void onGenerated(Palette palette) {
       // Here's your generated palette
    }
});

Six swatchs

We often use Vibrant and Dark Vibrant.

// Vibrant.
Palette.getVibrantSwatch()
// Vibrant dark.
Palette.getDarkVibrantSwatch()
// Vibrant light.
Palette.getLightVibrantSwatch()
// Muted.
Palette.getMutedSwatch()
// Muted dark.
Palette.getDarkMutedSwatch()
// Muted light.
Palette.getLightMutedSwatch()
// Call it to set the transparency to, let's say, 50%:
int halfTransparentColor = adjustAlpha(0xFFFFFFFF, 0.5f);
// After you got a color from palette, you can change color as like this way.
public int adjustAlpha(int color, float factor) {
int alpha = Math.round(Color.alpha(color) * factor);
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
return Color.argb(alpha, red, green, blue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment