Skip to content

Instantly share code, notes, and snippets.

@Temidtech
Created April 19, 2018 08:40
Show Gist options
  • Save Temidtech/5563e58311c3f8e9909c036517693c8e to your computer and use it in GitHub Desktop.
Save Temidtech/5563e58311c3f8e9909c036517693c8e to your computer and use it in GitHub Desktop.
Selecting Colors with the Palette API
// SetUp the Library
android {
compileSdkVersion 26
...
}
dependencies {
...
implementation 'com.android.support:palette-v7:27.1.1'
}
//////CREATE A PALETTE
// Generate palette synchronously and return it
public Palette createPaletteSync(Bitmap bitmap) {
Palette p = Palette.from(bitmap).generate();
return p;
}
// Generate palette asynchronously and use it on a different
// thread using onGenerated()
public void createPaletteAsync(Bitmap bitmap) {
Palette.from(bitmap).generate(new PaletteAsyncListener() {
public void onGenerated(Palette p) {
// Use generated instance
}
});
}
//// Use swatches to create color schemes
Palette.Swatch vibrant = myPalette.getVibrantSwatch();
if(vibrant != null){
int titleColor = vibrant.getTitleTextColor();
// ...
}
// The following snippet of code uses the methods from the above code snippets
//to synchronously generate a palette, get its vibrant swatch,
//and change the colors of a toolbar to match the bitmap image
// Set the background and text colors of a toolbar given a
// bitmap image to match
public void setToolbarColor(Bitmap bitmap) {
// Generate the palette and get the vibrant swatch
// See the createPaletteSync() method
// from the code snippet above
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = p.getVibrantSwatch();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// Load default colors
int backgroundColor = ContextCompat.getColor(getContext(),
R.color.default_title_background);
int textColor = ContextCompat.getColor(getContext(),
R.color.default_title_color);
// Check that the Vibrant swatch is available
if(vibrantSwatch != null){
backgroundColor = vibrantSwatch.getRgb();
textColor = vibrantSwatch.getTitleTextColor();
}
// Set the toolbar background and text colors
toolbar.setBackgroundColor(backgroundColor);
toolbar.setTitleTextColor(textColor);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment