Skip to content

Instantly share code, notes, and snippets.

@mataanin
Last active January 8, 2018 00:50
Show Gist options
  • Save mataanin/8d0bde2b2c8b10155e83897939a39061 to your computer and use it in GitHub Desktop.
Save mataanin/8d0bde2b2c8b10155e83897939a39061 to your computer and use it in GitHub Desktop.
Contrast logic
// Kotlin, Android min 19 SDK
private enum class Adjustment {
DARKEN,
LIGHTEN,
NONE
}
fun Context.adjustTextColor(color: Int, isHighContrastEnabled: Boolean): Int {
if (isHighContrastEnabled) {
return color
}
return when(checkAdjustment(color)) {
Adjustment.DARKEN -> Color.BLACK
Adjustment.LIGHTEN -> Color.WHITE
Adjustment.NONE -> color
}
}
fun Context.adjustTextColor(color: ColorStateList, isHighContrastEnabled: Boolean): ColorStateList {
return when (checkAdjustment(color.defaultColor)) {
Adjustment.DARKEN -> ColorStateList.valueOf(Color.BLACK)
Adjustment.LIGHTEN -> ColorStateList.valueOf(Color.WHITE)
Adjustment.NONE -> color
}
}
private fun isContrastTooSmall(color: Int, bgColor: Int): Boolean {
// WCAG 2.0 level AA requires a contrast ratio of 4.5:1
return ColorUtils.calculateContrast(color, bgColor) < 4.7f
}
private fun checkAdjustment(color: Int): Adjustment {
val luminance = ColorUtils.calculateLuminance(color)
if (luminance == 1.0 || luminance == 0.0) {
return Adjustment.NONE
}
if (luminance >= 0.5 && isContrastTooSmall(color, Color.BLACK)) {
return Adjustment.LIGHTEN
}
if (luminance < 0.5 && isContrastTooSmall(color, Color.WHITE)) {
return Adjustment.DARKEN
}
return Adjustment.NONE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment