colorToHSL function

Map<String, double> colorToHSL(
  1. Color color
)

Implementation

Map<String, double> colorToHSL(Color color) {
  // Convert hex to RGB first
  double r = color.red.toDouble();
  double g = color.green.toDouble();
  double b = color.blue.toDouble();
  // Then to HSL
  r /= 255;
  g /= 255;
  b /= 255;
  double cmin = min(min(r, g), b),
      cmax = max(max(r, g), b),
      delta = cmax - cmin,
      h = 0,
      s = 0,
      l = 0;

  if (delta == 0) {
    h = 0;
  } else if (cmax == r) {
    h = ((g - b) / delta) % 6;
  } else if (cmax == g) {
    h = (b - r) / delta + 2;
  } else {
    h = (r - g) / delta + 4;
  }

  // h = round(h * 60);
  h = (h * 60).roundToDouble();

  if (h < 0) h += 360;

  l = (cmax + cmin) / 2;
  s = delta == 0 ? 0 : delta / (1 - (2 * l - 1).abs());
  // s = +(s * 100).toFixed(1);
  s = double.parse((s * 100).toStringAsFixed(1));
  // l = +(l * 100).toFixed(1);
  l = double.parse((l * 100).toStringAsFixed(1));

  return {
    "h": h,
    "s": s,
    "l": l,
  };
}