我见过一些像 DataDex
这样的应用程序,我想它们有类似于卡片 View 和背景的动态颜色,我们可以在这里看到:
这种颜色也适用于细节 View :
我想这些颜色是从图像本身生成的,但我不知道正在使用哪个库或 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/