009_Palette调色板

本文介绍 Android Palette 库的使用方法,包括如何从图片中提取颜色并应用到 UI 中,实现界面颜色随图片变化的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 原理

Palette是一个类似调色板的工具类,根据传入的bitmap,提取出主体颜色,使得图片和颜色更加搭配,界面更协调。
Palette 可以从一张图片中提取颜色,我们可以把提取的颜色融入到App UI中,可以使UI风格更加美观融洽。比如,我们可以从图片中提取颜色设置给ActionBar做背景颜色,这样ActionBar的颜色就会随着显示图片的变化而变化。通俗的说,就是从一张图片中获取不同风格的源于图片的颜色

2 效果图

3 使用

1 compile 'com.android.support:palette-v7:23.4.0'
Palette可以提取的颜色如下:
● Vibrant (有活力的)
● Vibrant dark(有活力的 暗色)
● Vibrant light(有活力的 亮色)
● Muted (柔和的)
● Muted dark(柔和的 暗色)
● Muted light(柔和的 亮色)
第一步 compile 'com.android.support:palette-v7:23.4.0'
第一步,我们需要通过一个Bitmap对象来生成一个对应的Palette对象。 Palette 提供了四个静态方法用来生成对象。
● Palette generate(Bitmap bitmap)
● Palette generate(Bitmap bitmap, int numColors)
● generateAsync(Bitmap bitmap, PaletteAsyncListener listener)
● generateAsync(Bitmap bitmap, int numColors, final PaletteAsyncListener listener)
不难看出,生成方法分为generate(同步)和generateAsync(异步)两种,如果图片过大使用generate方法,可能会阻塞主线程,我们更倾向于使用generateAsync的方法,其实内部就是创建了一个AsyncTask。generateAsync方法需要一个PaletteAsyncListener对象用于监听生成完毕的回调。除了必须的Bitmap参数外,还可以传入一个numColors参数指定颜色数,默认是 16。
第二步,得到Palette对象后,就可以拿到提取到的颜色值
● Palette.getVibrantSwatch()
● Palette.getDarkVibrantSwatch()
● Palette.getLightVibrantSwatch()
● Palette.getMutedSwatch()
● Palette.getDarkMutedSwatch()
● Palette.getLightMutedSwatch()
第三步,使用颜色,上面get方法中返回的是一个 Swatch 样本对象,这个样本对象是Palette的一个内部类,它提供了一些获取最终颜色的方法。
● getPopulation(): 样本中的像素数量
● getRgb(): 颜色的RBG值
● getHsl(): 颜色的HSL值
● getBodyTextColor(): 主体文字的颜色值
● getTitleTextColor(): 标题文字的颜色值
通过 getRgb() 可以得到最终的颜色值并应用到UI中。getBodyTextColor() 和 getTitleTextColor() 可以得到此颜色下文字适合的颜色,这样很方便我们设置文字的颜色,使文字看起来更加舒服。

4 Demo

t1 = (TextView) findViewById(R.id. t1);
t2 = (TextView) findViewById(R.id. t2);
t3 = (TextView) findViewById(R.id. t3);
t4 = (TextView) findViewById(R.id. t4);
t5 = (TextView) findViewById(R.id. t5);
t6 = (TextView) findViewById(R.id. t6);
Bitmap bitmap = BitmapFactory. decodeResource(getResources(), R.drawable. f);
Palette. from(bitmap).generate( new Palette.PaletteAsyncListener() {
//发生主线程 Palette调色板 总共六种颜色
@Override
public void onGenerated(Palette palette) {
//柔和而暗的颜色
int darkMutedColor= palette.getDarkMutedColor(Color. BLUE);
//鲜艳和暗的颜色
int darkVibrantColor= palette.getDarkVibrantColor(Color. BLUE);
//亮和鲜艳的颜色
int lightVibrantColor=palette.getLightVibrantColor(Color. BLUE);
//亮和柔和的颜色
int lightMutedColor=palette.getLightMutedColor(Color. BLUE);
//柔和颜色
int mutedColor=palette.getMutedColor(Color. BLUE);
int vibrantColor=palette.getVibrantColor(Color. BLUE);
t1.setBackgroundColor(darkMutedColor);
t2.setBackgroundColor(darkVibrantColor);
t3.setBackgroundColor(lightVibrantColor);
t4.setBackgroundColor(lightMutedColor);
t5.setBackgroundColor(mutedColor);
t6.setBackgroundColor(vibrantColor);

5 效果

原始图片
ss
效果图
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值