toHSV method

HSVType toHSV()

Implementation

/*
 * Adapted from
 * http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
 */
HSVType toHSV() {
  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 v = max;
  final d = max - min;

  double h;
  double s;
  if (max == 0.0) {
    s = 0.0;
  } else {
    s = d / max;
  }

  if (max == min) {
    h = 0.0;
  } else {
    // 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 HSVType(h: h * 360, s: s, v: v, a: _a);

//2.2.0
//  Color.prototype.toHSV = 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, v = max;
//
//      var d = max - min;
//      if (max === 0) {
//          s = 0;
//      } else {
//          s = d / max;
//      }
//
//      if (max === min) {
//          h = 0;
//      } else {
//          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, v: v, a: a };
//  };
}