Android-界面设计-Palette-获得图片主要颜色【2019-附使用方法】

版权声明:个人学习记录,由于能力和时间有限,如果有错误望读者纠正,谢谢! 转载请注明出处 谢谢合作 https://blog.csdn.net/qq_43377749/article/details/87191086

1:用途说明

通常情况下,界面的 UI 不会随着内容的改变而改变(比如)图片切换而改变,如下图:

这时我们就用到了 Palette 获取图片中的颜色,并把它设置在空间中,是的界面更加美观:

2: 导入依赖

implementation 'com.android.support:palette-v7:28.0.0'

3: 使用举例

调用 Palette.from() 方法将bitmap传入,然后在回调中获取颜色值。

Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                Palette.Swatch vibrant = palette.getVibrantSwatch();
                if (vibrant == null) {
                    for (Palette.Swatch swatch : palette.getSwatches()) {
                        vibrant = swatch;
                        break;
                    }
                }
                // 这样获取的颜色可以进行改变。
                int rbg = vibrant.getRgb();

                // ... 省略一些无关紧要的代码
                imageView.setBackgroundColor(rbg);
                if (Build.VERSION.SDK_INT > 21) {
                    Window window = getWindow();
                    //状态栏改变颜色。
                    int color = changeColor(rbg);
                    window.setStatusBarColor(color);
                }

对于 Palette 获得的颜色 rbg 要进行如下换算:

private int changeColor(int rgb) {
    int red = rgb >> 16 & 0xFF;
    int green = rgb >> 8 & 0xFF;
    int blue = rgb & 0xFF;
    red = (int) Math.floor(red * (1 - 0.2));
    green = (int) Math.floor(green * (1 - 0.2));
    blue = (int) Math.floor(blue * (1 - 0.2));
    return Color.rgb(red, green, blue);
}

综上就能实现范例图片中的效果

猜你喜欢

转载自blog.csdn.net/qq_43377749/article/details/87191086