hslToRgb function

List<int> hslToRgb (
  1. num hue,
  2. num saturation,
  3. num lightness
)

Convert an HSL color to RGB, where h is specified in normalized degrees 0, 1 (where 1 is 360-degrees); s and l are in the range 0, 1. Returns a list r, g, b with values in the range 0, 255.

Implementation

List<int> hslToRgb(num hue, num saturation, num lightness) {
  if (saturation == 0) {
    var gray = (lightness * 255.0).toInt();
    return [gray, gray, gray];
  }

  num hue2rgb(num p, num q, num t) {
    if (t < 0.0) {
      t += 1.0;
    }
    if (t > 1) {
      t -= 1.0;
    }
    if (t < 1.0 / 6.0) {
      return p + (q - p) * 6.0 * t;
    }
    if (t < 1.0 / 2.0) {
      return q;
    }
    if (t < 2.0 / 3.0) {
      return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
    }
    return p;
  }

  var q = lightness < 0.5
      ? lightness * (1.0 + saturation)
      : lightness + saturation - lightness * saturation;
  var p = 2.0 * lightness - q;

  var r = hue2rgb(p, q, hue + 1.0 / 3.0);
  var g = hue2rgb(p, q, hue);
  var b = hue2rgb(p, q, hue - 1.0 / 3.0);

  return [(r * 255.0).round(), (g * 255.0).round(), (b * 255.0).round()];
}