Material Design整理(七)——Palette调色板

xiaoxiao2021-02-28  111

项目github地址 点击打开 喜欢就赏个star ^_^

简介

Palette的意思是调色板,它的作用是从图像中提取出突出的颜色,这样就可以将提取出来的颜色赋给状态栏、Toolbar、标题栏等,使得整个界面看起来色调统一,UI风格更加美观和融洽。

看上方效果图:可以看到,下面的6个条块的颜色是从图片中提取出来的,Palette可以提取的颜色有:

VibrantColor(有活力的颜色)LightVibrantColor(有活力的 亮色)DarkVibrantColor(有活力的 暗色)MutedColor(柔和的颜色)LightMutedColor(柔和的 亮色)DarkMutedColor(柔和的 暗色)

使用

1、添加依赖

compile 'com.android.support:palette-v7:26.0.0-alpha1'

2、代码调用

private void pickPicColors() { Bitmap bitmap = ((BitmapDrawable) iv_palette_img.getDrawable()).getBitmap(); Palette.Builder builder = Palette.from(bitmap); builder.generate(new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { // 提取有活力的颜色 int vibrantColor = palette.getVibrantColor(Color.RED); iv_vibrant.setBackgroundColor(vibrantColor); //提取有活力的 亮色 int lightVibrantColor = palette.getLightVibrantColor(Color.RED); iv_vibrant_light.setBackgroundColor(lightVibrantColor); //提取有活力的 暗色 int darkVibrantColor = palette.getDarkVibrantColor(Color.RED); iv_vibrant_dark.setBackgroundColor(darkVibrantColor); //提取柔和的颜色 int mutedColor = palette.getMutedColor(Color.RED); iv_muted.setBackgroundColor(mutedColor); //提取柔和的亮色 int lightMutedColor = palette.getLightMutedColor(Color.RED); iv_muted_light.setBackgroundColor(lightMutedColor); //提取柔和的暗色 int darkMutedColor = palette.getDarkMutedColor(Color.RED); iv_muted_dark.setBackgroundColor(darkMutedColor); } }); }

Palette也是使用建造者模式,先创建builder,通过调用Palette.from()得到Palette.Builder对象,一些配置可以通过builder来设置,我们只是使用默认的配置。

通过调用builder的generate方法分析图片,得到Palette对象,这里传入了一个Listener,该方法是异步执行,因为分析图像颜色需要时间,如果图片中颜色多样而且复杂,分析所消耗的事件也会越长,所以是通过接口回调分析完毕的结果。

得到Palette对象后,我们就可以通过它获取到6种色调,由于不一定能够提取到对应的色调,所以在调用每种方法的时候需要传入一个默认的颜色,如果提取不到对应的颜色,则是用默认颜色来代替。


3、获取样本 Swatch

Palette.Swatch vibrantSwatch = palette.getVibrantSwatch();//获取有活力的颜色样本 Palette.Swatch lightVibrantSwatch = palette.getLightVibrantSwatch();//获取有活力 亮色的样本 Palette.Swatch drakVibrantSwatch = palette.getDarkVibrantSwatch();//获取有活力 暗色的样本 Palette.Swatch mutedSwatch = palette.getMutedSwatch();//获取柔和的颜色样本 Palette.Swatch lightMutedSwatch = palette.getLightMutedSwatch();//获取柔和 亮色的样本 Palette.Swatch darkMutedSwatch = palette.getDarkMutedSwatch();//获取柔和 暗色的样本

使用Swatch的方法

int rgb = vibrantSwatch.getRgb();//获取对应样本的rgb float[] hsl = vibrantSwatch.getHsl();//获取hsl颜色 int population = vibrantSwatch.getPopulation();//获取像素的数量 int titleTextColor = vibrantSwatch.getTitleTextColor();//获取适合标题文字的颜色 int bodyTextColor = vibrantSwatch.getBodyTextColor();//获取适配内容文字的颜色

Palette除了可以获取到上面提到的6中色调外,还可以获取到对应的Swatch对象,Swatch是样本的意思,Swatch样本对象中,可以获取色调的RGB颜色,HSL颜色,像素的数量等,同时,还提供了相当牛逼的方法,getTitleTextColor()和getBodyTextColor(),获取适合作为图片上方标题和内容文字的颜色,如:

int titleColor=vibrantSwatch.getTitleTextColor(); int contentColor=vibrantSwatch.getBodyTextColor(); tv_palette_title.setTextColor(titleColor); tv_palette_content.setTextColor(contentColor);
转载请注明原文地址: https://www.6miu.com/read-78268.html

最新回复(0)