Is there a way to programmatically compute what th...
# compose
a
Is there a way to programmatically compute what the color “onColor” should be given a color? For example, if my dynamic color is white, then the “onColor” must be Black. Or, if my given color changes from White to Blue, then the onColor must also change to from Black to White for text legibility. Is there a way to accomplish this?
👋 1
g
Hey Archie, there is a
Colors.contentColorFor(backgroundColor: Color)
in compose material, not sure if that’s what you’re looking for.
1
👋 1
But it’s working for material set. Or are you looking for an actual algorithm?
👋 1
z
There’s no one right answer - it’s up your designers, accessibility guidelines, etc.
c
What @georgiy.shur mentioned above is what we use internally for components. @Louis Pullen-Freilich [G] can elaborate more also if there's other suggestions
But also as Zach said, sometimes that contentColorFor calculation still may not get you the desired result, and you'll have to adjust accordingly in conversations with your designers (if any) and also consider a11y contrast requirements
a
Hi guys, thank you very much for the replies. I am aware of
contentColorFor(...)
But doesn’t that just depend on the defined color in the material theme?
Copy code
fun Colors.contentColorFor(backgroundColor: Color): Color {
    return when (backgroundColor) {
        primary -> onPrimary
        primaryVariant -> onPrimary
        secondary -> onSecondary
        secondaryVariant -> onSecondary
        background -> onBackground
        surface -> onSurface
        error -> onError
        else -> Color.Unspecified
    }
}
t
I faced the problem with a custom color picker. I ended up with the following:
Copy code
fun Color.getContrastColor(): Color = if (luminance() > 0.5) Color.Black else Color.White
But as the others said, this does not necessarily conform to accessability standards. But it works well enough for my usecase.
🤔 1