Skip to content

Commit

Permalink
[Catalog][a11y] Select text color based on optimal contrast against b…
Browse files Browse the repository at this point in the history
…ackground

PiperOrigin-RevId: 632242630
  • Loading branch information
paulfthomas authored and dsn5ft committed May 13, 2024
1 parent 9451acd commit b301a58
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions catalog/java/io/material/catalog/color/ColorDemoUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,20 @@

import android.graphics.Color;
import androidx.annotation.ColorInt;
import com.google.android.material.color.MaterialColors;
import androidx.core.graphics.ColorUtils;

/** Utility methods for Color. */
final class ColorDemoUtils {

private ColorDemoUtils() {}

static int getTextColor(@ColorInt int backgroundColor) {
// Use white text color if the background color is considered dark.
return MaterialColors.isColorLight(backgroundColor) ? Color.BLACK : Color.WHITE;
// Use the text color with the best contrast against the background color.
if (ColorUtils.calculateContrast(Color.BLACK, backgroundColor)
> ColorUtils.calculateContrast(Color.WHITE, backgroundColor)) {
return Color.BLACK;
} else {
return Color.WHITE;
}
}
}

0 comments on commit b301a58

Please sign in to comment.