【问题标题】:Android How to set dynamic background color from specific ImageAndroid 如何从特定图像设置动态背景颜色
【发布时间】:2020-06-30 14:05:09
【问题描述】:

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

此颜色也适用于详细视图:

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

【问题讨论】:

标签: android android-studio android-fragments android-cardview


【解决方案1】:

您可以使用 Palettes 使用动态颜色。 Material Design 鼓励动态使用颜色,尤其是当您需要处理丰富的图像时。新的Palette support library 可让您从图像中提取一小组颜色来设置您的 UI 控件的样式以匹配;创造身临其境的体验。

您可以通过两种方式实现 Palettes:

同步:

Palette palette = Palette.from(bitmap).generate();
// OR
Palette palette = Palette.from(bitmap).maximumColorCount(numberOfColors).generate();

传入的位图是要从中提取颜色的图像。默认情况下,它将使用 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());
}

异步:

通过将PaletteAsyncListener 传递给 generate 方法,它现在将使用 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());
          }
    }
});

更多信息,请查看documentation。

【讨论】:

猜你喜欢
  • 2022-06-12
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2019-08-21
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
相关资源
最近更新 更多