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

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

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

enter image description here

这种颜色也适用于细节 View :

enter image description here

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

最佳答案

您可以使用调色板 来使用动态颜色。 Material Design 鼓励动态使用颜色,尤其是当您要处理丰富的图像时。新的 Palette 支持库 允许您从图像中提取一小组颜色来设置您的 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 传递给生成方法,它现在将使用 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 .

关于Android如何从特定图像设置动态背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62659282/

相关文章:

android - 如何在 Android 上使用 DataBinding 测试 MVVM

Java 方法在 Eclipse 中可用,但在 Android 中不可用

android - 更改软件包名称,现在在应用程序中会出现一个弹出窗口

android - ViewFlipper 与 fragment

android - EventBus 在同一 fragment 中发布和订阅

java - 应用程序找不到 SD 卡内的图像目录

android - 是否可以支持旧 API 级别的 setScrollY() (ScrollView API 14) 之类的函数?

android - 无法在 Android Studio 中生成已签名的 APK 提示我找不到 proguard-rules.txt 错误?

android - 构建后字符在 strings.xml 中变成问号

安卓 fragment 布局