color_secuence.dart 2.44 KB
Newer Older
1 2
part of sprites;

3 4 5 6
/// A sequence of colors representing a gradient or a color transition over
/// time. The sequence is represented by a list of [colors] and a list of
/// [colorStops], the stops are normalized values (0.0 to 1.0) and ordered in
/// the list. Both lists have the same number of elements.
7
class ColorSequence {
8
  /// List of colors.
9
  List<Color> colors;
10 11

  /// List of color stops, normalized values (0.0 to 1.0) and ordered.
12 13
  List<double> colorStops;

14 15
  /// Creates a new color sequence from a list of [colors] and a list of
  /// [colorStops].
16 17 18 19 20 21
  ColorSequence(this.colors, this.colorStops) {
    assert(colors != null);
    assert(colorStops != null);
    assert(colors.length == colorStops.length);
  }

22
  /// Creates a new color sequence from a start and an end color.
23 24 25 26 27
  ColorSequence.fromStartAndEndColor(Color start, Color end) {
    colors = [start, end];
    colorStops = [0.0, 1.0];
  }

28
  /// Creates a new color sequence by copying an existing sequence.
29 30 31 32 33
  ColorSequence.copy(ColorSequence sequence) {
    colors = new List<Color>.from(sequence.colors);
    colorStops = new List<double>.from(sequence.colorStops);
  }

34 35 36
  /// Returns the color at a normalized (0.0 to 1.0) position in the color
  /// sequence. If a color stop isn't hit, the returned color will be an
  /// interpolation of a color between two color stops.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  Color colorAtPosition(double pos) {
    assert(pos >= 0.0 && pos <= 1.0);

    double lastStop = colorStops[0];
    Color lastColor = colors[0];

    for (int i = 0; i < colors.length; i++) {
      double currentStop = colorStops[i];
      Color currentColor = colors[i];

      if (pos <= currentStop) {
        double blend = (pos - lastStop) / (currentStop - lastStop);
        return _interpolateColor(lastColor, currentColor, blend);
      }
      lastStop = currentStop;
      lastColor = currentColor;
    }
    return colors[colors.length-1];
  }
}

Color _interpolateColor(Color a, Color b, double blend) {
  double aa = a.alpha.toDouble();
  double ar = a.red.toDouble();
  double ag = a.green.toDouble();
  double ab = a.blue.toDouble();

  double ba = b.alpha.toDouble();
  double br = b.red.toDouble();
  double bg = b.green.toDouble();
  double bb = b.blue.toDouble();

  int na = (aa * (1.0 - blend) + ba * blend).toInt();
  int nr = (ar * (1.0 - blend) + br * blend).toInt();
  int ng = (ag * (1.0 - blend) + bg * blend).toInt();
  int nb = (ab * (1.0 - blend) + bb * blend).toInt();

  return new Color.fromARGB(na, nr, ng, nb);
}