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



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

我知道在新的材料指南下这是可能的,但是我找不到任何关于它的文档。

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

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

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

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

generate(Bitmap)
generate(Bitmap, int)

您可以在这里阅读更多-在这里输入链接描述

好的,所以我从Akasha所说的开始,但是generate在最新版本中已被弃用。因此,我最终做了以下操作:

// 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)

来设置所需视图的背景

最新更新