hsiToRgb static method

RgbColor hsiToRgb(
  1. HsiColor hsiColor
)

Converts a HSI color to a RGB color.

Implementation

static RgbColor hsiToRgb(HsiColor hsiColor) {
  final hsi = hsiColor.toFactoredList();

  var hue = hsi[0] * math.pi * 2;
  final saturation = hsi[1];
  final intensity = hsi[2];

  final pi3 = math.pi / 3;

  double red, green, blue;

  final firstValue = intensity * (1 - saturation);

  double calculateSecondValue(double hue) =>
      intensity * (1 + (saturation * math.cos(hue) / math.cos(pi3 - hue)));

  double calculateThirdValue(double hue) =>
      intensity *
      (1 + (saturation * (1 - (math.cos(hue) / math.cos(pi3 - hue)))));

  if (hue < 2 * pi3) {
    blue = firstValue;
    red = calculateSecondValue(hue);
    green = calculateThirdValue(hue);
  } else if (hue < 4 * pi3) {
    hue = hue - (2 * pi3);
    red = firstValue;
    green = calculateSecondValue(hue);
    blue = calculateThirdValue(hue);
  } else {
    hue = hue - (4 * pi3);
    green = firstValue;
    blue = calculateSecondValue(hue);
    red = calculateThirdValue(hue);
  }

  // The calculated RGB values, in some cases, may
  // exceed 1.0 by up to 0.0000000000000002.
  if (red > 1) red = 1;
  if (green > 1) green = 1;
  if (blue > 1) blue = 1;

  final alpha = hsiColor.alpha / 255;

  return RgbColor.extrapolate(<double>[red, green, blue, alpha]);
}