tween.dart 16.2 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:ui' show Color, Size, Rect;
6

7 8
import 'package:flutter/foundation.dart';

9 10
import 'animation.dart';
import 'animations.dart';
11
import 'curves.dart';
12

13 14
// Examples can assume:
// Animation<Offset> _animation;
15
// AnimationController _controller;
16

17 18 19 20 21
/// An object that can produce a value of type `T` given an [Animation<double>]
/// as input.
///
/// Typically, the values of the input animation are nominally in the range 0.0
/// to 1.0. In principle, however, any value could be provided.
22 23
///
/// The main subclass of [Animatable] is [Tween].
24
abstract class Animatable<T> {
25 26
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
27
  const Animatable();
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  /// Returns the value of the object at point `t`.
  ///
  /// The value of `t` is nominally a fraction in the range 0.0 to 1.0, though
  /// in practice it may extend outside this range.
  ///
  /// See also:
  ///
  ///  * [evaluate], which is a shorthand for applying [transform] to the value
  ///    of an [Animation].
  ///  * [Curve.transform], a similar method for easing curves.
  T transform(double t);

  /// The current value of this object for the given [Animation].
  ///
  /// This function is implemented by deferring to [transform]. Subclasses that
  /// want to provide custom behavior should override [transform], not
  /// [evaluate].
  ///
  /// See also:
  ///
  ///  * [transform], which is similar but takes a `t` value directly instead of
  ///    an [Animation].
  ///  * [animate], which creates an [Animation] out of this object, continually
  ///    applying [evaluate].
  T evaluate(Animation<double> animation) => transform(animation.value);
54

55
  /// Returns a new [Animation] that is driven by the given animation but that
56
  /// takes on values determined by this object.
57 58 59 60 61 62 63 64
  ///
  /// Essentially this returns an [Animation] that automatically applies the
  /// [evaluate] method to the parent's value.
  ///
  /// See also:
  ///
  ///  * [AnimationController.drive], which does the same thing from the
  ///    opposite starting point.
65
  Animation<T> animate(Animation<double> parent) {
66
    return _AnimatedEvaluation<T>(parent, this);
67
  }
68

69
  /// Returns a new [Animatable] whose value is determined by first evaluating
70
  /// the given parent and then evaluating this object.
71 72
  ///
  /// This allows [Tween]s to be chained before obtaining an [Animation].
73
  Animatable<T> chain(Animatable<double> parent) {
74
    return _ChainedEvaluation<T>(parent, this);
75
  }
76 77
}

78
class _AnimatedEvaluation<T> extends Animation<T> with AnimationWithParentMixin<double> {
79
  _AnimatedEvaluation(this.parent, this._evaluatable);
80

81
  @override
82
  final Animation<double> parent;
83

84
  final Animatable<T> _evaluatable;
85

86
  @override
87
  T get value => _evaluatable.evaluate(parent);
88 89 90

  @override
  String toString() {
91
    return '$parent\u27A9$_evaluatable\u27A9$value';
92 93 94 95 96 97
  }

  @override
  String toStringDetails() {
    return '${super.toStringDetails()} $_evaluatable';
  }
98 99
}

100
class _ChainedEvaluation<T> extends Animatable<T> {
101 102
  _ChainedEvaluation(this._parent, this._evaluatable);

103 104
  final Animatable<double> _parent;
  final Animatable<T> _evaluatable;
105

106
  @override
107 108
  T transform(double t) {
    return _evaluatable.transform(_parent.transform(t));
109
  }
110 111 112 113 114

  @override
  String toString() {
    return '$_parent\u27A9$_evaluatable';
  }
115 116
}

117
/// A linear interpolation between a beginning and ending value.
118 119 120
///
/// [Tween] is useful if you want to interpolate across a range.
///
121
/// To use a [Tween] object with an animation, call the [Tween] object's
122
/// [animate] method and pass it the [Animation] object that you want to
123
/// modify.
124
///
125
/// You can chain [Tween] objects together using the [chain] method, so that a
126
/// single [Animation] object is configured by multiple [Tween] objects called
127
/// in succession. This is different than calling the [animate] method twice,
128
/// which results in two separate [Animation] objects, each configured with a
129
/// single [Tween].
130
///
131
/// {@tool sample}
132 133 134
///
/// Suppose `_controller` is an [AnimationController], and we want to create an
/// [Animation<Offset>] that is controlled by that controller, and save it in
135 136 137 138 139 140 141 142 143 144
/// `_animation`. Here are two possible ways of expressing this:
///
/// ```dart
/// _animation = _controller.drive(
///   Tween<Offset>(
///     begin: const Offset(100.0, 50.0),
///     end: const Offset(200.0, 300.0),
///   ),
/// );
/// ```
145 146
/// {@end-tool}
/// {@tool sample}
147 148
///
/// ```dart
149
/// _animation = Tween<Offset>(
150 151
///   begin: const Offset(100.0, 50.0),
///   end: const Offset(200.0, 300.0),
152
/// ).animate(_controller);
153
/// ```
154
/// {@end-tool}
155
///
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
/// In both cases, the `_animation` variable holds an object that, over the
/// lifetime of the `_controller`'s animation, returns a value
/// (`_animation.value`) that depicts a point along the line between the two
/// offsets above. If we used a [MaterialPointArcTween] instead of a
/// [Tween<Offset>] in the code above, the points would follow a pleasing curve
/// instead of a straight line, with no other changes necessary.
///
/// ## Performance optimizations
///
/// Tweens are mutable; specifically, their [begin] and [end] values can be
/// changed at runtime. An object created with [Animation.drive] using a [Tween]
/// will immediately honor changes to that underlying [Tween] (though the
/// listeners will only be triggered if the [Animation] is actively animating).
/// This can be used to change an animation on the fly without having to
/// recreate all the objects in the chain from the [AnimationController] to the
/// final [Tween].
///
173
/// If a [Tween]'s values are never changed, however, a further optimization can
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
/// be applied: the object can be stored in a `static final` variable, so that
/// the exact same instance is used whenever the [Tween] is needed. This is
/// preferable to creating an identical [Tween] afresh each time a [State.build]
/// method is called, for example.
///
/// ## Types with special considerations
///
/// Classes with [lerp] static methods typically have corresponding dedicated
/// [Tween] subclasses that call that method. For example, [ColorTween] uses
/// [Color.lerp] to implement the [ColorTween.lerp] method.
///
/// Types that define `+` and `-` operators to combine values (`T + T → T` and
/// `T - T → T`) and an `*` operator to scale by multiplying with a double (`T *
/// double → T`) can be directly used with `Tween<T>`.
///
/// This does not extend to any type with `+`, `-`, and `*` operators. In
/// particular, [int] does not satisfy this precise contract (`int * double`
/// actually returns [num], not [int]). There are therefore two specific classes
/// that can be used to interpolate integers:
///
///  * [IntTween], which is an approximation of a linear interpolation (using
///    [double.round]).
///  * [StepTween], which uses [double.floor] to ensure that the result is
///    never greater than it would be using if a `Tween<double>`.
///
/// The relevant operators on [Size] also don't fulfill this contract, so
/// [SizeTween] uses [Size.lerp].
///
/// In addition, some of the types that _do_ have suitable `+`, `-`, and `*`
/// operators still have dedicated [Tween] subclasses that perform the
/// interpolation in a more specialized manner. One such class is
/// [MaterialPointArcTween], which is mentioned above. The [AlignmentTween], and
/// [AlignmentGeometryTween], and [FractionalOffsetTween] are another group of
/// [Tween]s that use dedicated `lerp` methods instead of merely relying on the
/// operators (in particular, this allows them to handle null values in a more
/// useful manner).
210
class Tween<T extends dynamic> extends Animatable<T> {
211 212
  /// Creates a tween.
  ///
213 214 215
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
216
  Tween({ this.begin, this.end });
217 218

  /// The value this variable has at the beginning of the animation.
219
  ///
220 221
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
222 223 224
  T begin;

  /// The value this variable has at the end of the animation.
225
  ///
226 227
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
228 229 230
  T end;

  /// Returns the value this variable has at the given animation clock value.
231
  ///
232 233 234
  /// The default implementation of this method uses the [+], [-], and [*]
  /// operators on `T`. The [begin] and [end] properties must therefore be
  /// non-null by the time this method is called.
235
  @protected
236 237 238 239 240
  T lerp(double t) {
    assert(begin != null);
    assert(end != null);
    return begin + (end - begin) * t;
  }
241

242
  /// Returns the interpolated value for the current value of the given animation.
243
  ///
244 245 246
  /// This method returns `begin` and `end` when the animation values are 0.0 or
  /// 1.0, respectively.
  ///
247 248 249
  /// This function is implemented by deferring to [lerp]. Subclasses that want
  /// to provide custom behavior should override [lerp], not [transform] (nor
  /// [evaluate]).
250 251 252 253
  ///
  /// See the constructor for details about whether the [begin] and [end]
  /// properties may be null when this is called. It varies from subclass to
  /// subclass.
254
  @override
255
  T transform(double t) {
256 257 258 259 260 261
    if (t == 0.0)
      return begin;
    if (t == 1.0)
      return end;
    return lerp(t);
  }
262

263
  @override
264
  String toString() => '$runtimeType($begin \u2192 $end)';
265 266
}

267 268 269
/// A [Tween] that evaluates its [parent] in reverse.
class ReverseTween<T> extends Tween<T> {
  /// Construct a [Tween] that evaluates its [parent] in reverse.
270 271 272
  ReverseTween(this.parent)
    : assert(parent != null),
      super(begin: parent.end, end: parent.begin);
273 274 275 276 277 278 279 280 281 282 283 284

  /// This tween's value is the same as the parent's value evaluated in reverse.
  ///
  /// This tween's [begin] is the parent's [end] and its [end] is the parent's
  /// [begin]. The [lerp] method returns `parent.lerp(1.0 - t)` and its
  /// [evaluate] method is similar.
  final Tween<T> parent;

  @override
  T lerp(double t) => parent.lerp(1.0 - t);
}

285
/// An interpolation between two colors.
286
///
287 288 289 290
/// This class specializes the interpolation of [Tween<Color>] to use
/// [Color.lerp].
///
/// See [Tween] for a discussion on how to use interpolation objects.
291
class ColorTween extends Tween<Color> {
292
  /// Creates a [Color] tween.
293
  ///
294
  /// The [begin] and [end] properties may be null; the null value
295 296 297 298 299 300
  /// is treated as transparent.
  ///
  /// We recommend that you do not pass [Colors.transparent] as [begin]
  /// or [end] if you want the effect of fading in or out of transparent.
  /// Instead prefer null. [Colors.transparent] refers to black transparent and
  /// thus will fade out of or into black which is likely unwanted.
301 302
  ColorTween({ Color begin, Color end }) : super(begin: begin, end: end);

303
  /// Returns the value this variable has at the given animation clock value.
304
  @override
305 306 307
  Color lerp(double t) => Color.lerp(begin, end, t);
}

308
/// An interpolation between two sizes.
309
///
310 311 312 313
/// This class specializes the interpolation of [Tween<Size>] to use
/// [Size.lerp].
///
/// See [Tween] for a discussion on how to use interpolation objects.
314
class SizeTween extends Tween<Size> {
315
  /// Creates a [Size] tween.
316
  ///
317 318
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty size.
319 320
  SizeTween({ Size begin, Size end }) : super(begin: begin, end: end);

321
  /// Returns the value this variable has at the given animation clock value.
322
  @override
323 324 325
  Size lerp(double t) => Size.lerp(begin, end, t);
}

326
/// An interpolation between two rectangles.
327
///
328 329 330 331
/// This class specializes the interpolation of [Tween<Rect>] to use
/// [Rect.lerp].
///
/// See [Tween] for a discussion on how to use interpolation objects.
332
class RectTween extends Tween<Rect> {
333
  /// Creates a [Rect] tween.
334
  ///
335 336
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty rect at the top left corner.
337 338
  RectTween({ Rect begin, Rect end }) : super(begin: begin, end: end);

339
  /// Returns the value this variable has at the given animation clock value.
340
  @override
341 342 343
  Rect lerp(double t) => Rect.lerp(begin, end, t);
}

344
/// An interpolation between two integers that rounds.
345
///
346
/// This class specializes the interpolation of [Tween<int>] to be
347 348 349 350
/// appropriate for integers by interpolating between the given begin
/// and end values and then rounding the result to the nearest
/// integer.
///
351 352 353 354
/// This is the closest approximation to a linear tween that is possible with an
/// integer. Compare to [StepTween] and [Tween<double>].
///
/// See [Tween] for a discussion on how to use interpolation objects.
355
class IntTween extends Tween<int> {
356 357
  /// Creates an int tween.
  ///
358 359 360
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
361 362 363 364
  IntTween({ int begin, int end }) : super(begin: begin, end: end);

  // The inherited lerp() function doesn't work with ints because it multiplies
  // the begin and end types by a double, and int * double returns a double.
365
  @override
366 367
  int lerp(double t) => (begin + (end - begin) * t).round();
}
368

369 370
/// An interpolation between two integers that floors.
///
371
/// This class specializes the interpolation of [Tween<int>] to be
372
/// appropriate for integers by interpolating between the given begin
373
/// and end values and then using [double.floor] to return the current
374 375 376 377
/// integer component, dropping the fractional component.
///
/// This results in a value that is never greater than the equivalent
/// value from a linear double interpolation. Compare to [IntTween].
378 379
///
/// See [Tween] for a discussion on how to use interpolation objects.
380
class StepTween extends Tween<int> {
381
  /// Creates an [int] tween that floors.
382
  ///
383 384 385
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
386 387 388 389
  StepTween({ int begin, int end }) : super(begin: begin, end: end);

  // The inherited lerp() function doesn't work with ints because it multiplies
  // the begin and end types by a double, and int * double returns a double.
390
  @override
391 392 393
  int lerp(double t) => (begin + (end - begin) * t).floor();
}

394 395 396 397 398 399 400 401 402 403 404 405 406
/// A tween with a constant value.
class ConstantTween<T> extends Tween<T> {
  /// Create a tween whose [begin] and [end] values equal [value].
  ConstantTween(T value) : super(begin: value, end: value);

  /// This tween doesn't interpolate, it always returns [value].
  @override
  T lerp(double t) => begin;

  @override
  String toString() => '$runtimeType(value: begin)';
}

407 408 409 410 411
/// Transforms the value of the given animation by the given curve.
///
/// This class differs from [CurvedAnimation] in that [CurvedAnimation] applies
/// a curve to an existing [Animation] object whereas [CurveTween] can be
/// chained with another [Tween] prior to receiving the underlying [Animation].
412 413 414 415
/// ([CurvedAnimation] also has the additional ability of having different
/// curves when the animation is going forward vs when it is going backward,
/// which can be useful in some scenarios.)
///
416
/// {@tool sample}
417 418 419 420 421
///
/// The following code snippet shows how you can apply a curve to a linear
/// animation produced by an [AnimationController] `controller`:
///
/// ```dart
422
/// final Animation<double> animation = _controller.drive(
423 424 425
///   CurveTween(curve: Curves.ease),
/// );
/// ```
426
/// {@end-tool}
427 428 429 430 431 432
///
/// See also:
///
///  * [CurvedAnimation], for an alternative way of expressing the sample above.
///  * [AnimationController], for examples of creating and disposing of an
///    [AnimationController].
433
class CurveTween extends Animatable<double> {
434 435 436
  /// Creates a curve tween.
  ///
  /// The [curve] argument must not be null.
437 438
  CurveTween({ @required this.curve })
    : assert(curve != null);
439

440
  /// The curve to use when transforming the value of the animation.
441 442
  Curve curve;

443
  @override
444
  double transform(double t) {
445 446 447 448 449 450
    if (t == 0.0 || t == 1.0) {
      assert(curve.transform(t).round() == t);
      return t;
    }
    return curve.transform(t);
  }
451 452 453

  @override
  String toString() => '$runtimeType(curve: $curve)';
454
}