createKeyColor static method

Hct createKeyColor(
  1. double hue,
  2. double chroma
)

Creates a key color from a hue and a chroma. The key color is the first tone, starting from T50, matching the given hue and chroma. Key color Hct

Implementation

static Hct createKeyColor(double hue, double chroma) {
  double startTone = 50.0;
  Hct smallestDeltaHct = Hct.from(hue, chroma, startTone);
  double smallestDelta = (smallestDeltaHct.chroma - chroma).abs();
  // Starting from T50, check T+/-delta to see if they match the requested
  // chroma.
  //
  // Starts from T50 because T50 has the most chroma available, on
  // average. Thus it is most likely to have a direct answer and minimize
  // iteration.
  for (double delta = 1.0; delta < 50.0; delta += 1.0) {
    // Termination condition rounding instead of minimizing delta to avoid
    // case where requested chroma is 16.51, and the closest chroma is 16.49.
    // Error is minimized, but when rounded and displayed, requested chroma
    // is 17, key color's chroma is 16.
    if (chroma.round() == smallestDeltaHct.chroma.round()) {
      return smallestDeltaHct;
    }

    final Hct hctAdd = Hct.from(hue, chroma, startTone + delta);
    final double hctAddDelta = (hctAdd.chroma - chroma).abs();
    if (hctAddDelta < smallestDelta) {
      smallestDelta = hctAddDelta;
      smallestDeltaHct = hctAdd;
    }

    final Hct hctSubtract = Hct.from(hue, chroma, startTone - delta);
    final double hctSubtractDelta = (hctSubtract.chroma - chroma).abs();
    if (hctSubtractDelta < smallestDelta) {
      smallestDelta = hctSubtractDelta;
      smallestDeltaHct = hctSubtract;
    }
  }

  return smallestDeltaHct;
}