Palette是Google官方提供的一个类,用于帮助开发者提取图片的主色。
1、生成 Palette
根据bitmap生成 Palette
//同步方法,应该在子线程中使用
Palette p = Palette.generate(bitmap);
//异步方法
Palette.from(bitmap).generate(new PaletteAsyncListener() {
public void onGenerated(Palette p) {
// Use generated instance
}
});
2、 提取主色
Palette 主要会解析下面几种颜色:
- Vibrant(鲜艳色)
- Vibrant Dark(鲜艳色中的暗色)
- Vibrant Light(鲜艳色中的亮色)
- Muted(柔和色)
- Muted Dark(柔和色中的暗色)
- Muted Light(柔和色中的亮色)
举例如下:
Swatch表示从图像的调色板生成的颜色样本,通过Swatch提供的方法获取颜色的相关信息:
Palette.Swatch s = p.getVibrantSwatch(); //获取到充满活力的这种色调
Palette.Swatch s = p.getDarkVibrantSwatch(); //获取充满活力的黑
Palette.Swatch s = p.getLightVibrantSwatch(); //获取充满活力的亮
Palette.Swatch s = p.getMutedSwatch(); //获取柔和的色调
Palette.Swatch s = p.getDarkMutedSwatch(); //获取柔和的黑
Palette.Swatch s = p.getLightMutedSwatch(); //获取柔和的亮
Palette.Swatch s = p.getDominantSwatch(); //返回从调色板中占主导地位的样本。
可以从Swatch中获取RGB颜色值、HSL颜色向量、对应颜色在图像中所占的比例等信息
/**
* @return this swatch's RGB color value
*/
@ColorInt
public int getRgb() {
return mRgb;
}
/**
* Return this swatch's HSL values.
* hsv[0] is Hue [0 .. 360)
* hsv[1] is Saturation [0...1]
* hsv[2] is Lightness [0...1]
*/
@NonNull
public float[] getHsl() {
if (mHsl == null) {
mHsl = new float[3];
}
ColorUtils.RGBToHSL(mRed, mGreen, mBlue, mHsl);
return mHsl;
}
/**
* @return the number of pixels represented by this swatch
*/
public int getPopulation() {
return mPopulation;
}
3、提取主色原理
/**
* Returns the dominant swatch from the palette.
*
* <p>The dominant swatch is defined as the swatch with the greatest population (frequency)
* within the palette.</p>
*/
@Nullable
public Swatch getDominantSwatch() {
return mDominantSwatch;
}
/**
* Returns the color of the dominant swatch from the palette, as an RGB packed int.
*
* @param defaultColor value to return if the swatch isn't available
* @see #getDominantSwatch()
*/
@ColorInt
public int getDominantColor(@ColorInt int defaultColor) {
return mDominantSwatch != null ? mDominantSwatch.getRgb() : defaultColor;
}
@Nullable
private Swatch findDominantSwatch() {
int maxPop = Integer.MIN_VALUE;
Swatch maxSwatch = null;
for (int i = 0, count = mSwatches.size(); i < count; i++) {
Swatch swatch = mSwatches.get(i);
if (swatch.getPopulation() > maxPop) {
maxSwatch = swatch;
maxPop = swatch.getPopulation();
}
}
return maxSwatch;
}
系统默认提供获取16种颜色的Swatch,获取最大Population(颜色在图像中所占的比例)的Swatch,获取其RGB颜色值。
系统默认提供16种颜色的Swatch: