android palette组件用法,Palette颜色提取使用详解

如果你试过android Lollipop的sdk,你可能注意到了Palette。Palette从图像中提取突出的颜色,这样可以把色值赋给ActionBar、或者其他,可以让界面整个色调统一。

521dbf3faa2112fc507cf90c5b371146.png

创建Palette实例

有四种创建实例的方法:// Synchronous methods.

// --------------------------------

// These should be used when you have access to the underlying image loading thread.

// Picasso allows this through a Transformation. For other libraries, YMMV.

// Uses the default palette size (16).

Palette p = Palette.generate(bitmap);

// Allows you to specify the maximum palette size, in this case 24.

Palette p = Palette.generate(bitmap, 24);

// Asynchronous methods

// --------------------------------

// This is the quick and easy integration path. Internally uses an AsyncTask so

// this may not be optimal (since you're dipping in and out of threads)

// Uses the default palette size (16).

Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {

@Override

public void onGenerated(Palette palette) {

// Here's your generated palette

}

});

// Allows you to specify the maximum palette size, in this case 24.

Palette.generateAsync(bitmap, 24, new Palette.PaletteAsyncListener() {

@Override

public void onGenerated(Palette palette) {

// Here's your generated palette

}

});

创建完一个实例之后,我们还需要得到一种采集的样本(swatch),有6中样本(swatch):Vibrant. Palette.getVibrantSwatch()

Vibrant dark. Palette.getDarkVibrantSwatch()

Vibrant light. Palette.getLightVibrantSwatch()

Muted. Palette.getMutedSwatch()

Muted dark. Palette.getDarkMutedSwatch()

Muted light. Palette.getLightMutedSwatch()

具体选择哪一种取决于你自己,大多数情况下我们都使用Vibrant and Dark Vibrant。

使用样本(swatch)

swatch有以下方法:getPopulation(): the amount of pixels which this swatch represents.

getRgb(): the RGB value of this color.

getHsl(): the HSL value of this color.

getBodyTextColor(): the RGB value of a text color which can be displayed on top of this color.

getTitleTextColor(): the RGB value of a text color which can be displayed on top of this color.

比如如果你的TextView 有个背景图片,要想让字体颜色能够和背景图片匹配,则使用getBodyTextColor()比较合适,getTitleTextColor()其实应该和getBodyTextColor()差不多。

下面的代码则是展示了如何从一张图片中提取颜色将textView的背景色设置成图片的主色调,然后再使用getTitleTextColor()来设置一个匹配的文字颜色。Palette.Swatch swatch = palette.getVibrantSwatch();

TextView titleView = ...;

if (swatch != null) {

titleView.setBackgroundColor(swatch.getRgb());

titleView.setTextColor(swatch.getTitleTextColor());

}

需要注意的是getVibrantSwatch()可能会返回一个null值,所以检查一下是必须的。

size的问题

你还可以使用如下方法一次性获得所有的swatch:List swatches = palette.getSwatches();

在上面的代码中,你可能注意到了可以设置palette的size。size越大,花费的时间越长,而越小,可以选择的色彩也越小。最佳的选择是根据image的用途:

头像之类的,size最好在24-32之间;

风景大图之类的 size差不多在8-16;

默认是16.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值