moreVisibleColor function

Color moreVisibleColor(
  1. Color foregroundColor,
  2. Color backgroundColor, [
  3. double percent = 0.4
])

Returns a color that is more visible against the specified background color.

If the brightness difference between the foreground and background colors is greater than percent, the foreground color is returned. Otherwise, a new color is returned with a brightness value that is more visible against the background color.

Implementation

Color moreVisibleColor(
  Color foregroundColor,
  Color backgroundColor, [
  // percent is the desired brightness diff.
  double percent = 0.4,
]) {
  final foregroundLuminance = foregroundColor.computeLuminance();
  final backgroundLuminance = backgroundColor.computeLuminance();
  final brightnessDiff = foregroundLuminance - backgroundLuminance;

  if (brightnessDiff.abs() >= percent) return foregroundColor;

  final sign = brightnessDiff.isNegative ? -1 : 1;
  final newBrightness = min(max(0, foregroundLuminance + sign * percent), 1);
  return foregroundColor.withLightness(newBrightness.toDouble());
}