HSLColor.fromColor constructor

HSLColor.fromColor(
  1. Color color
)

Creates an HSLColor from an RGB Color.

This constructor does not necessarily round-trip with toColor because of floating point imprecision.

Implementation

factory HSLColor.fromColor(Color color) {
  final double red = color.red / 0xFF;
  final double green = color.green / 0xFF;
  final double blue = color.blue / 0xFF;

  final double max = math.max(red, math.max(green, blue));
  final double min = math.min(red, math.min(green, blue));
  final double delta = max - min;

  final double alpha = color.alpha / 0xFF;
  final double hue = _getHue(red, green, blue, max, delta);
  final double lightness = (max + min) / 2.0;
  // Saturation can exceed 1.0 with rounding errors, so clamp it.
  final double saturation = lightness == 1.0
    ? 0.0
    : clampDouble(delta / (1.0 - (2.0 * lightness - 1.0).abs()), 0.0, 1.0);
  return HSLColor.fromAHSL(alpha, hue, saturation, lightness);
}