From d96124443cdf01d47966e6fc1e1b7b1027e5d7d9 Mon Sep 17 00:00:00 2001 From: Naveen Singh Date: Thu, 5 Jun 2025 18:43:31 +0530 Subject: [PATCH] feat: improve contrast utilities --- .../org/fossify/commons/extensions/Int.kt | 29 ++++++++++++++----- .../org/fossify/commons/helpers/Constants.kt | 3 ++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/commons/src/main/kotlin/org/fossify/commons/extensions/Int.kt b/commons/src/main/kotlin/org/fossify/commons/extensions/Int.kt index cabcf310fb..b374173a8b 100644 --- a/commons/src/main/kotlin/org/fossify/commons/extensions/Int.kt +++ b/commons/src/main/kotlin/org/fossify/commons/extensions/Int.kt @@ -6,15 +6,17 @@ import android.graphics.Color import android.media.ExifInterface import android.os.Handler import android.os.Looper +import androidx.core.graphics.ColorUtils import androidx.core.os.postDelayed import org.fossify.commons.helpers.DARK_GREY +import org.fossify.commons.helpers.WCAG_AA_NORMAL import java.text.DecimalFormat import java.util.Locale import java.util.Random fun Int.getContrastColor(): Int { - val y = (299 * Color.red(this) + 587 * Color.green(this) + 114 * Color.blue(this)) / 1000 - return if (y >= 149 && this != Color.BLACK) DARK_GREY else Color.WHITE + val luminance = ColorUtils.calculateLuminance(this) + return if (luminance > 0.5) DARK_GREY else Color.WHITE } fun Int.toHex() = String.format("#%06X", 0xFFFFFF and this).uppercase(Locale.getDefault()) @@ -192,11 +194,22 @@ fun Int.countdown(intervalMillis: Long, callback: (count: Int) -> Unit) { } } -fun Int.adjustSimColorForBackground(bg: Int): Int { - val hsv = FloatArray(3) - Color.colorToHSV(bg, hsv) - if (hsv[2] < 0.5) { - return this.lightenColor(24) +fun Int.adjustForContrast( + background: Int, + minContrast: Double = WCAG_AA_NORMAL, +): Int { + var color = this + var alpha = 0f + val target = if (ColorUtils.calculateLuminance(background) < 0.5) { + Color.WHITE + } else { + Color.BLACK + } + + while (ColorUtils.calculateContrast(color, background) < minContrast && alpha < 1f) { + alpha += 0.05f + color = ColorUtils.blendARGB(this, target, alpha) } - return this + + return color } diff --git a/commons/src/main/kotlin/org/fossify/commons/helpers/Constants.kt b/commons/src/main/kotlin/org/fossify/commons/helpers/Constants.kt index 9acad9168f..a2cf444ba0 100644 --- a/commons/src/main/kotlin/org/fossify/commons/helpers/Constants.kt +++ b/commons/src/main/kotlin/org/fossify/commons/helpers/Constants.kt @@ -60,6 +60,9 @@ const val HIGHER_ALPHA = 0.75f const val LOWER_ALPHA_INT = 30 const val MEDIUM_ALPHA_INT = 90 +const val WCAG_AA_NORMAL = 4.5 +const val WCAG_AA_LARGE = 3.0 + const val HOUR_MINUTES = 60 const val DAY_MINUTES = 24 * HOUR_MINUTES const val WEEK_MINUTES = DAY_MINUTES * 7