最近公司的項目升級到了AndroidX,項目里依賴的第三方庫也同時升了一波版本號漂羊,Gilde升級到4.9.0后一些老的api都過時了,記錄下獲取主色調(diào)這個功能點的代碼。
第一步
通過Glide獲取Bitmap對象狂窑,升級后的api寫法如下:
Glide.with(mContext)
.asBitmap()
.load(url)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap>?) {
PaletteHelper.setPaletteColor(bitmap, guild_title_bg)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when
// imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})
glide幫我們處理好了子線程耗時操作
第二步
通過Palette類從Bitmap獲取色調(diào),新增依賴如下
implementation "androidx.palette:palette:1.0.0"
實現(xiàn)方法如下:
/**
* 主色調(diào)工具類
*/
public class PaletteHelper {
/**
* 設(shè)置圖片主色調(diào)
*
* @param bitmap
* @return
*/
public static void setPaletteColor(Bitmap bitmap, final View view) {
if (bitmap == null) {
return;
}
Palette.from(bitmap).maximumColorCount(10).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(@NonNull Palette palette) {
// List<Palette.Swatch> list = palette.getSwatches();
// int colorSize = 0;
// Palette.Swatch maxSwatch = null;
// for (int i = 0; i < list.size(); i++) {
// Palette.Swatch swatch = list.get(i);
// if (swatch != null) {
// int population = swatch.getPopulation();
// if (colorSize < population) {
// colorSize = population;
// maxSwatch = swatch;
// }
// }
// }
Palette.Swatch s = palette.getDominantSwatch();//獨特的一種
Palette.Swatch s1 = palette.getVibrantSwatch(); //獲取到充滿活力的這種色調(diào)
Palette.Swatch s2 = palette.getDarkVibrantSwatch(); //獲取充滿活力的黑
Palette.Swatch s3 = palette.getLightVibrantSwatch(); //獲取充滿活力的亮
Palette.Swatch s4 = palette.getMutedSwatch(); //獲取柔和的色調(diào)
Palette.Swatch s5 = palette.getDarkMutedSwatch(); //獲取柔和的黑
Palette.Swatch s6 = palette.getLightMutedSwatch(); //獲取柔和的亮
if (s1 != null) {
view.setBackgroundColor(s1.getRgb());
}
}
});
}
}
代碼比較簡單桑腮,如果看完覺得有幫到你的話泉哈,希望能點個贊~