如何在Android中获取图像中最突出的颜色

3
我注意到 WhatsApp Android 应用有一个功能,可以从用户的图像中获取最突出的颜色,并将其设置为工具栏颜色。我尝试遍历一张图片并获取最突出的颜色,但遍历速度太慢了。WhatsApp 可以轻松完成此操作,请问有没有做过这种操作的人能向我展示如何实现?另外,当活动刚打开时,如何将我的 CollapsingToolbar 默认设置为折叠状态?我注意到默认情况下它是展开状态,但我希望它首先处于折叠状态,用户可以通过滚动来展开它。谢谢!
2个回答

4

我不能代表WhatsApp使用的策略,但支持库确实提供了'com.android.support:palette-v7:23.1.1',可以为你完成这个任务。

Palette.generate(Bitmap toGetColorsFrom)
Palette.generate(Bitmap toGetColorsFrom, int maximumPaletteSize)
Palette.generateAsync(Bitmap toGetColorsFrom, PaletteAsyncListener listener)
Palette.generateAsync(Bitmap toGetColorsFrom, int maximumPaletteSize, PaletteAsyncListener listener)

异步方法需要Palette.PaletteAsyncListener来通知您结果。从这些方法中收到Palette对象后,您可以像这样设置工具栏背景颜色:
Palette palette = Palette.generate(myBitmap);
Palette.Swatch swatch = palette.getVibrantSwatch();
toolbar.setBackgroundColor(swatch.getRgb());

请注意,getVibrantSwatch()是获取一组颜色的一种方式。你也可以使用以下方法:
Palette.getVibrantSwatch()
Palette.getDarkVibrantSwatch()
Palette.getLightVibrantSwatch()
Palette.getMutedSwatch()
Palette.getDarkMutedSwatch()
Palette.getLightMutedSwatch()

1

关于颜色,可以使用调色板库

如果要在活动打开时设置折叠工具栏为关闭状态,您可以在活动中使用以下代码:

AppBarLayout layout = (AppBarLayout) findViewById(R.id.appbarID); layout.setExpanded(false);//这里的appbarID是包含折叠式工具栏的xml文件中的appbarlayout的ID

希望对您有所帮助。


我的CollapingToolbar中没有setExpanded方法。 - life evader
使用AppBarLayout而不是CollapsingToolbar来调用该方法。 - farhan patel
好的,也许我有点混淆了,这是我的代码: mParent = (CoordinatorLayout) findViewById(R.id.parentCord); final Toolbar toolbar = (Toolbar) findViewById(R.id.anim_toolbar); collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); 我该如何折叠collapsingToolbar? - life evader
我明白了,谢谢。但是它有点慢,我先看到了背后的图像,不过还是谢谢。 - life evader

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接