android 5.x—Palette图片取色调

在android的版本更新历程中,UI美观越发成为Google发展的重心。Material Design是谷歌推出的全新的设计语言规范,旨在为手机、平板、台式机和“其他平台”提供更为一致、更广泛的“外观和感觉“。

在android 5.x中提出了Palette提取图片颜色的概念,这样便可以把色值付给ActionBar,其他View,让整个界面保持统一的色调。

使用Palette需要引入库com.android.support:palette-v7:23.2.0(版本号可能不相同)。然后传递一个Bitmap对象给Palette,并调用Palette.generate()静态方法或者Palette.generateAsync()方法创建一个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
    }
});

然后可以得到6中采集的颜色样本(Swatch),

//  充满活力的色调
Palette.Swatch vibrantSwatch = palette.getVibrantSwatch();
//  充满活力的亮色调
Palette.Swatch lightVibrantSwatch = palette.getLightVibrantSwatch();
//  充满活力的暗色调
Palette.Swatch darkVibrantSwatch = palette.getDarkVibrantSwatch();

//  柔和的色调
Palette.Swatch mutedSwatch = palette.getMutedSwatch();
//  柔和的亮色调
Palette.Swatch lightMuteSwatch = palette.getLightMutedSwatch();
//  柔和的暗色调
Palette.Swatch darkMutedSwatch = palette.getDarkMutedSwatch();

需要注意的是,上述获取的Palette.Swatch对象可能为null,因此,在使用该对象时,必须对null值判断。

Swatch有如下方法:

// the amount of pixels which this swatch represents
getPopulation();
// the RGB value of this color
getRgb();
// the HSL value of this color
getHsl();
// the RGB value of a text color which can be displayed on top of this color
getBodyTextColor();
//  the RGB value of a text color which can be displayed on top of this color
getTitleTextColor();

讲了这么多,现在看看使用的效果图:
android 5.x—Palette图片取色调_第1张图片

demo下载链接

你可能感兴趣的:(android,Palette)