針對(duì)Bitmap:
/**
* 應(yīng)用顏色效果到指定的位圖上,包括亮度、對(duì)比度和飽和度的調(diào)整。
*
* @param brightness 亮度值,范圍為0到100,其中50表示沒(méi)有變化。
* @param contrast 對(duì)比度值,范圍為0到100,其中50表示沒(méi)有變化。
* @param saturation 飽和度值,范圍為0到100,其中50表示灰度,100表示完全飽和。
*/
private fun applyColorEffect(
brightness: Int,
contrast: Int,
saturation: Int,
bitmap: Bitmap
) {
// 計(jì)算并設(shè)置亮度
val lum = (brightness - 50) * 2 * 0.3f * 255 * 0.01f
val brightnessArray = floatArrayOf(
1f, 0f, 0f, 0f, lum,
0f, 1f, 0f, 0f, lum,
0f, 0f, 1f, 0f, lum,
0f, 0f, 0f, 1f, 0f
)
colorMatrix.set(brightnessArray)
// 計(jì)算并設(shè)置對(duì)比度
val scale = (contrast - 50 + 100) / 100f
val offset = 0.5f * (1 - scale) + 0.5f
val contrastArray =
floatArrayOf(
scale, 0f, 0f, 0f, offset,
0f, scale, 0f, 0f, offset,
0f, 0f, scale, 0f, offset,
0f, 0f, 0f, 1f, 0f
)
colorMatrix.postConcat(ColorMatrix(contrastArray))
// 設(shè)置飽和度
val saturationMatrix = ColorMatrix()
saturationMatrix.setSaturation(((saturation - 50) / 50) * 0.3f + 1)
colorMatrix.postConcat(saturationMatrix)
// 創(chuàng)建顏色過(guò)濾器,用于之后的繪制操作
val colorFilter = ColorMatrixColorFilter(colorMatrix)
// 創(chuàng)建畫(huà)筆,并設(shè)置顏色過(guò)濾器
val paint = Paint().apply {
this.colorFilter = colorFilter
}
// 創(chuàng)建畫(huà)布,并在新的位圖上繪制原位圖,應(yīng)用之前設(shè)置的顏色效果
val canvas = Canvas(resultBitmap!!)
canvas.drawBitmap(bitmap, 0f, 0f, paint)
// 將應(yīng)用了效果的位圖顯示到ImageView上
iv.setImageBitmap(resultBitmap)
}
直接通過(guò)ImageView的colorFilter:
/**
* 應(yīng)用顏色效果到指定的位圖上,包括亮度、對(duì)比度和飽和度的調(diào)整。
*
* @param brightness 亮度值,范圍為0到100,其中50表示沒(méi)有變化。
* @param contrast 對(duì)比度值,范圍為0到100,其中50表示沒(méi)有變化。
* @param saturation 飽和度值,范圍為0到100,其中50表示灰度,100表示完全飽和。
*/
private fun applyColorEffect(
brightness: Int,
contrast: Int,
saturation: Int,
) {
val colorMatrix = ColorMatrix()
// 計(jì)算并設(shè)置亮度
val lum = (brightness - 50) * 2 * 0.3f * 255 * 0.01f
val brightnessArray = floatArrayOf(
1f, 0f, 0f, 0f, lum,
0f, 1f, 0f, 0f, lum,
0f, 0f, 1f, 0f, lum,
0f, 0f, 0f, 1f, 0f
)
colorMatrix.set(brightnessArray)
// 計(jì)算并設(shè)置對(duì)比度
val scale = (contrast - 50 + 100) / 100f
val offset = 0.5f * (1 - scale) + 0.5f
val contrastArray =
floatArrayOf(
scale, 0f, 0f, 0f, offset,
0f, scale, 0f, 0f, offset,
0f, 0f, scale, 0f, offset,
0f, 0f, 0f, 1f, 0f
)
colorMatrix.postConcat(ColorMatrix(contrastArray))
// 設(shè)置飽和度
val saturationMatrix = ColorMatrix()
saturationMatrix.setSaturation(((saturation - 50) / 50) * 0.3f + 1)
colorMatrix.postConcat(saturationMatrix)
// 創(chuàng)建并設(shè)置ColorMatrixColorFilter
val colorFilter = ColorMatrixColorFilter(colorMatrix)
iv.colorFilter = colorFilter
}