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) {
    final 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;
  }

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

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

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