使用Palette提取颜色

使用Palette提取当前图片的颜色,然后根据提取的颜色去设置当前主题的颜色,可以让主题动态适应当前页面的色调,做到整个APP颜色基调统一。

使用支持库

使用Palette要配置对应的Support Library。

1
2
3
4
5
6
7
8
9
android {
compileSdkVersion 24
...
}

dependencies {
...
implementation 'com.android.support:palette-v7:24.2.1'
}

创建Palette

下面介绍如何根据一个Bitmap创建一个Palette。

生成Palette实例

生成Palette有同步和异步两种方式,同步方式是在当前UI线程中操作,如果想优化UI性能,可以使用异步方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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
}
});
}

自定义Palette

生成Palette的时可以使用Palette.Builder对象自定义Palette,比如,可以过滤掉图片中黑色,或者只是用图片的上半部分生成Palette。

可以使用以下方法跳转Palette的大小和颜色:

  • addFilter():添加颜色过滤器;
  • maximumColorCount():设置生成Palette所使用的最大颜色位数,默认值是16位;
  • setRegion():设置生成Palette的图片区域;
  • addTarget():通过Target.Builder为Palette添加自定义的目标颜色配置;

获取颜色

一般Palette会抽取下面6中特征颜色:

  • Light Vibrant:充满活力的亮
  • Vibrant:充满活力的
  • Dark Vibrant:充满活力的黑
  • Light Muted:柔和的亮
  • Muted:柔和的
  • Dark Muted:柔和的黑

下面以一张图说明这些颜色特征:

palette-color-profiles

具体获取某个特征颜色使用Palette.getXXXColor()方法,比如getMutedColor()。并不是所有的图片都会返回这些颜色特效,所以,在获取颜色时,还需要提供一个默认的返回颜色。

使用Swatch创建配色方案

对于每个颜色特征,Palette都提供了一个Palette.Swatch对象用于生产对应的配色方案,获取Palette.Swatch模板代码如下:

1
2
3
4
5
6
7
8
// Return a palette's vibrant swatch after checking that it exists
private Palette.Swatch checkVibrantSwatch(Palette p) {
Palette.Swatch vibrant = p.getVibrantSwatch();
if (vibrant != null) {
return vibrant;
}
// Throw error
}

注意要检查返回的Swatch是否为空,因为getXXXSwatch()方法没有像getXXXColor()方法那样设置默认的颜色。

获取了Swatch后,就可以根据Swatch创建主题的配色方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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() and checkVibrantSwatch() methods
// from the code snippets above
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);

// Set the toolbar background and text colors
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setBackgroundColor(vibrantSwatch.getRgb());
toolbar.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}

下图是使用Vibrant特征颜色生成的Toolbar配色方法:

palette-color-scheme

坚持原创技术分享,您的支持将鼓励我继续创作!