colorsNearestRGB function

List<String> colorsNearestRGB(
  1. String color, [
  2. int n = 3
])

The n css colors that are nearest in rgb space to color.

Example:

final color = "rgb(10, 20, 30)";
for (final c in colorsNearestRGB(color, 3)) {
  print(c);
}

Output:

black
midnightblue
darkslategray

Implementation

List<String> colorsNearestRGB(String color, [int n = 3]) {
  final ps = ColorProperties(color),
      red = ps.red,
      green = ps.green,
      blue = ps.blue,
      distanceTuple = (String color) {
        final ps = ColorProperties(color),
            r = ps.red - red,
            g = ps.green - green,
            b = ps.blue - blue,
            squareDistance = r * r + g * g + b * b;
        return (color, squareDistance);
      },
      colorDistances = [...Color.colorData.keys.map(distanceTuple)]
        ..sort(_byDistance);

  return [...colorDistances.sublist(0, n).map(_getColor)];
}