https://kotlinlang.org logo
#compose
Title
# compose
a

Archie

11/23/2021, 5:25 PM
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

georgiy.shur

11/23/2021, 7:05 PM
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

Zach Klippenstein (he/him) [MOD]

11/23/2021, 7:12 PM
There’s no one right answer - it’s up your designers, accessibility guidelines, etc.
c

Chris Sinco [G]

11/24/2021, 3:32 AM
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

Archie

11/24/2021, 6:11 AM
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

Tobias Suchalla

11/24/2021, 6:18 AM
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