rgbToHsp static method

HspColor rgbToHsp(
  1. RgbColor rgbColor
)

Converts a RGB color to a HSP color.

Implementation

static HspColor rgbToHsp(RgbColor rgbColor) {
  if (rgbColor.isBlack) return HspColor(0, 0, 0, rgbColor.alpha);
  if (rgbColor.isWhite) return HspColor(0, 0, 100, rgbColor.alpha);
  if (rgbColor.isMonochromatic) {
    return HspColor(0, 0, rgbColor.red / 255 * 100, rgbColor.alpha);
  }

  final rgb = rgbColor.toFactoredList();

  final red = rgb[0];
  final green = rgb[1];
  final blue = rgb[2];

  final percievedBrightness = math
      .sqrt((red * red * _pr) + (green * green * _pg) + (blue * blue * _pb));

  final max = rgb.reduce(math.max);
  final min = rgb.reduce(math.min);

  double? hue;
  late double saturation;

  if (max == min) {
    hue = 0;
    saturation = 0;
  } else if (max == red) {
    saturation = 1 - ((blue >= green) ? green / red : blue / red);
  } else if (max == green) {
    saturation = 1 - ((red >= blue) ? blue / green : red / green);
  } else {
    saturation = 1 - ((green >= red) ? red / blue : green / blue);
  }

  hue ??= getHue(rgbColor);

  final alpha = rgbColor.alpha / 255;

  return HspColor.extrapolate(
      <double>[hue, saturation, percievedBrightness, alpha]);
}