readableOn static method

Color readableOn(
  1. Color c,
  2. List<Color> backgrounds, {
  3. double ratio = 4.5,
})

c moved towards black or white in small steps until it reaches ratio against every colour in backgrounds (opaque: blend a translucent tint over its base with Color.alphaBlend first).

Implementation

static Color readableOn(Color c, List<Color> backgrounds, {double ratio = 4.5}) {
  bool ok(Color x) => backgrounds.every((b) => contrastRatio(x, b) >= ratio);
  if (ok(c)) return c;
  final avg = backgrounds.fold<double>(0, (s, b) => s + b.computeLuminance()) / backgrounds.length;
  final target = avg > 0.4 ? const Color(0xFF000000) : const Color(0xFFFFFFFF);
  for (var i = 1; i <= 20; i++) {
    final x = Color.lerp(c, target, i / 20)!;
    if (ok(x)) return x;
  }
  return target;
}