使用调色板Palette在背景图中取色

Palette是android.support.v7.graphics包中定义的用于提取背景中的颜色的类,该类用final修饰,不可被继承。

在使用Palette前,需要在build.gradle中加入依赖:

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

Palette可提取的颜色按类型可分为以下几种:

  • Vibrant ——动感的
  • Vibrant Dark ——动感的亮
  • Vibrant Light ——动感的暗
  • Muted ——柔和的
  • Muted Dark ——柔和的亮
  • Muted Light ——柔和的暗

Palette采用工厂模式(Builder)创建调色板对象,如下所示:

Palette.Builder builder = Palette.from(BitmapFactory.decodeResource(getResources(), R.mipmap.picture));

下面将按照Palette的取色类型提取相应颜色:

 builder.generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                Palette.Swatch vibrant = palette.getVibrantSwatch();
                if (vibrant != null) {
                    TextView textView = (TextView) findViewById(R.id.vibrant);
                    textView.setBackgroundColor(vibrant.getBodyTextColor());
                }

                Palette.Swatch vibrantlight = palette.getLightVibrantSwatch();
                if (vibrantlight != null) {
                    TextView textView = (TextView) findViewById(R.id.vibrant_light);
                    textView.setBackgroundColor(vibrantlight.getBodyTextColor());
                }

                Palette.Swatch vibrantdark = palette.getDarkVibrantSwatch();
                if (vibrantdark != null) {
                    TextView textView = (TextView) findViewById(R.id.vibrant_dark);
                    textView.setBackgroundColor(vibrantdark.getBodyTextColor());
                }


                Palette.Swatch muted = palette.getMutedSwatch();
                if (muted != null) {
                    TextView textView = (TextView) findViewById(R.id.muted);
                    textView.setBackgroundColor(muted.getBodyTextColor());
                }


                Palette.Swatch mutedDark = palette.getDarkMutedSwatch();
                if (mutedDark != null) {
                    TextView textView = (TextView) findViewById(R.id.muted_dark);
                    textView.setBackgroundColor(mutedDark.getBodyTextColor());
                }


                Palette.Swatch mutedLight = palette.getLightMutedSwatch();
                if (mutedLight != null) {
                    TextView textView = (TextView) findViewById(R.id.muted_light);
                    textView.setBackgroundColor(mutedLight.getBodyTextColor());
                }

            }
        });

展示的图片及提取的颜色样本(左下角依次排列)见下图:


从左至右依次为Vibrant (动感的)、Vibrant Dark (动感的亮)、Vibrant Light (动感的暗)、Muted (柔和的)、Muted Dark (柔和的亮)、Muted Light (柔和的暗)

你可能感兴趣的:(Palette,取色器,调色板)