toHSL method

HSLType toHSL()

Returns this Color as HSLA

Implementation

HSLType toHSL() {
  final _r = red;
  final _g = green;
  final _b = blue;
  final _a = alpha.toDouble();

  final rawMap = <String, double>{'r': _r, 'g': _g, 'b': _b};

  // maxMap = { 'r or g or b': max_value, ..., 'r or g or b': min_value }.
  // Repeated values removed.
  final maxMap = SplayTreeMap<String, double>.of(
      rawMap, (String a, String b) => rawMap[b].compareTo(rawMap[a]));

  final max = maxMap[maxMap.firstKey()];
  final min = maxMap[maxMap.lastKey()];

  final l = (max + min) / 2;
  final d = max - min;

  double h;
  double s;
  if (max == min) {
    h = s = 0.0;
  } else {
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

    // max
    switch (maxMap.firstKey()) {
      case 'r':
        h = (_g - _b) / d + (_g < _b ? 6 : 0);
        break;
      case 'g':
        h = (_b - _r) / d + 2;
        break;
      case 'b':
        h = (_r - _g) / d + 4;
        break;
    }
    h /= 6;
  }

  return HSLType(h: h * 360, s: s, l: l, a: _a);

//2.2.0
//  Color.prototype.toHSL = function () {
//      var r = this.rgb[0] / 255,
//          g = this.rgb[1] / 255,
//          b = this.rgb[2] / 255,
//          a = this.alpha;
//
//      var max = Math.max(r, g, b), min = Math.min(r, g, b);
//      var h, s, l = (max + min) / 2, d = max - min;
//
//      if (max === min) {
//          h = s = 0;
//      } else {
//          s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
//
//          switch (max) {
//              case r: h = (g - b) / d + (g < b ? 6 : 0); break;
//              case g: h = (b - r) / d + 2;               break;
//              case b: h = (r - g) / d + 4;               break;
//          }
//          h /= 6;
//      }
//      return { h: h * 360, s: s, l: l, a: a };
//  };
}