动态获取可绘制对象的原色以设置工具栏颜色

Dynamically get primary color of drawable to set toolbar color

我有一个 android 应用程序,其中包含用于详细视图的折叠工具栏布局。我正在尝试根据传入的可绘制对象的原色动态设置工具栏的颜色。

我知道新的 material 准则可以做到这一点,但我找不到任何相关文档。

为此,请将以下依赖项添加到您的 gradle 文件

dependencies {
  compile 'com.android.support:palette-v7:21.0.0'
}

然后您可以使用 generate 方法,该方法要么只接受一个位图对象,要么使用一个整数指定调色板应生成的颜色数的位图。

默认情况下,此方法将尝试从提供的位图中生成 16 种颜色。

generate(Bitmap)
generate(Bitmap, int)

您可以在此处阅读更多信息 - enter link description here

好的,所以我从 Akasha 所说的开始,但生成在最新版本中已被弃用。所以我最终做了以下事情。

// Get reference to icon drawable
Drawable iconDrawable = mPackageHelper.getAppIcon(mApp.getAppPackage());

Bitmap iconBitmap = ((BitmapDrawable) iconDrawable).getBitmap();

Palette iconPalette = Palette.from(iconBitmap).maximumColorCount(16).generate();

int primaryColorInt = iconPalette.getVibrantColor(0x000000);

mToolbar.setBackgroundColor(primaryColorInt);
collapsingToolbar.setBackgroundColor(primaryColorInt);

这个解决方案对我有用。我在 onResourceReady 回调中调用解决方案,同时使用 Glide 图像加载库,该库为回调提供 resource: Drawable? 参数,然后我将其传递给下面的函数以获取主色调。如果主色不存在,0 是默认颜色。

首先在你的build.gradle中包含正确的依赖:

implementation "androidx.palette:palette:1.0.0"

然后使用相关资源调用此函数:

private fun getDominantColor(resource: Drawable?): Int {
    return Palette.from((resource as BitmapDrawable).bitmap)
        .maximumColorCount(16)
        .generate().getDominantColor(0)
}

然后通过将响应传递给 targetView.setBackgroundColor(dominantColor)

来设置所需视图的背景