Java的同学可参考JAVA 图像分析-主要颜色
前端的同学可参考palette.js
IOS的同学可参考Google Palette算法详解以及OC化
本篇使用谷歌的Palette库来实现
效果图
添加依赖
//Android
implementation 'com.android.support:palette-v7:29.0.0'
//AndroidX
implementation 'androidx.palette:palette:1.0.0'
代码
object PaletteUtils {
/**
* 回调接口
*/
interface IAnalyzeColor {
fun result(result: ArrayList<ColorInfo>)
}
data class ColorInfo(
//颜色
val color: Int,
//颜色占比
val percentage: Float
)
/**
* 从bitmap获取主色调及权重
*/
fun paletteColor(bitmap: Bitmap, iColor: IAnalyzeColor?) {
val builder = Palette.from(bitmap)
builder.maximumColorCount(8)
builder.generate { palette ->
palette?.let {
val swatches = palette.swatches
swatches.forEach {
ALog.v("Palette", "${it.bodyTextColor} ${it.population}")
}
//这里取权重靠前的五个颜色
val take = swatches.toMutableList().sortedByDescending { it.population }.take(5)
val sum = take.sumBy { it.population }
val result = ArrayList<ColorInfo>(take.size)
take.forEach {
result.add(ColorInfo(it.rgb, it.population.toFloat() / sum))
}
iColor?.result(result)
}
}
}
}
Demo
由于代码不多,想实践的话可复用此demo