Android 如何从特定图像设置动态背景颜色

Nex*_*nts 5 android android-fragments android-studio android-cardview

我见过一些类似的应用程序,DataDex我想它们有像卡片视图和背景的动态颜色这样的东西,我们可以在这里看到:

在此输入图像描述

这种颜色也适用于细节视图:

在此输入图像描述

我认为这些颜色是从 IMAGE 本身生成的,但我不知道正在使用哪个库或 API。有什么提示吗?

Sha*_*T D 2

您可以使用动态颜色PalettesMaterial Design鼓励动态地使用颜色,尤其是当您有丰富的图像可供使用时。新功能Palette support library可让您从图像中提取一小组颜色,以匹配您的 UI 控件的样式;创造身临其境的体验。

您可以通过两种方式实现调色板:

同步:

Palette palette = Palette.from(bitmap).generate();
// OR
Palette palette = Palette.from(bitmap).maximumColorCount(numberOfColors).generate();
Run Code Online (Sandbox Code Playgroud)

传入的位图是要从中提取颜色的图像。默认情况下,它将使用最大 16 种颜色的调色板大小。然后我们可以使用如下所示的颜色。

// Pick one of the swatches
Palette.Swatch vibrant = palette.getVibrantSwatch();
if (vibrant != null) {
    // Set the background color of a layout based on the vibrant color
    containerView.setBackgroundColor(vibrant.getRgb());
    // Update the title TextView with the proper text color
    titleView.setTextColor(vibrant.getTitleTextColor());
}
Run Code Online (Sandbox Code Playgroud)

异步:

通过将 a 传递PaletteAsyncListener给生成方法,它现在将使用 AsyncTask 异步生成调色板,以从位图中收集调色板样本信息:

// This is the quick and easy integration path. 
// May not be optimal (since you're dipping in and out of threads)
Palette.from(bitmap).maximumColorCount(numberOfColors).generate(new Palette.PaletteAsyncListener() {
    @Override
    public void onGenerated(Palette palette) {
         // Get the "vibrant" color swatch based on the bitmap
         Palette.Swatch vibrant = palette.getVibrantSwatch();
          if (vibrant != null) {
              // Set the background color of a layout based on the vibrant color
              containerView.setBackgroundColor(vibrant.getRgb());
              // Update the title TextView with the proper text color
              titleView.setTextColor(vibrant.getTitleTextColor());
          }
    }
});
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看文档