Updated on 2026-08-14

This commit is contained in:
Tangem 2023-10-11 10:57:11 +04:00
parent 7141c0e6ee
commit 91ec85c3eb
12 changed files with 269 additions and 93 deletions

View file

@ -0,0 +1,44 @@
package com.tangem.core.ui.utils
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.compose.ui.graphics.Color
import androidx.core.graphics.ColorUtils
import androidx.core.graphics.drawable.toBitmap
import androidx.palette.graphics.Palette
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class ImageBackgroundContrastChecker(
private val image: Bitmap,
private val backgroundColor: Int,
) {
constructor(drawable: Drawable, backgroundColor: Int) : this(
image = drawable.toBitmap(),
backgroundColor = backgroundColor,
)
suspend fun getContrastColorIfNeeded(isDarkTheme: Boolean): Color {
return if (isLowContrast()) {
if (isDarkTheme) Color.White else Color.Black
} else {
Color.Transparent
}
}
suspend fun isLowContrast(): Boolean {
val palette = generatePaletteAsync(bitmap = image)
val color = palette.getDominantColor(backgroundColor)
val contrast = ColorUtils.calculateContrast(color, backgroundColor)
return contrast <= LOW_CONTRAST_RATIO
}
private suspend fun generatePaletteAsync(bitmap: Bitmap): Palette = withContext(Dispatchers.Default) {
return@withContext Palette.Builder(bitmap).generate()
}
private companion object {
// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
private const val LOW_CONTRAST_RATIO = 1.5f
}
}