|
| 1 | +import 'package:flutter/animation.dart'; |
| 2 | + |
| 3 | +/// An animation that transforms the value of another animation from a certain range to another. |
| 4 | +/// |
| 5 | +/// This animation proxies the parent animation, but enforces the minimum and maximum values |
| 6 | +/// in the [toMin] and [toMax] range. |
| 7 | +/// |
| 8 | +/// *From* values should be less than *max* values. |
| 9 | +/// |
| 10 | +/// Example usage: |
| 11 | +/// ```dart |
| 12 | +/// final TransformedAnimation animation = TransformedAnimation( |
| 13 | +/// parent: parent, |
| 14 | +/// fromMin: 0.0, |
| 15 | +/// fromMax: 1.0, |
| 16 | +/// toMin: 0.0, |
| 17 | +/// toMax: 10.0, |
| 18 | +/// ); |
| 19 | +/// ``` |
| 20 | +/// Here `animation.value` will always be between 0.0 and 10.0, inclusive. |
| 21 | +class TransformedAnimation extends Animation<double> with AnimationWithParentMixin<double> { |
| 22 | + /// Creates a transformed animation with an invariant range. |
| 23 | + /// |
| 24 | + /// The [parent] animation is the source of values for this animation. |
| 25 | + /// The [fromMin] and [fromMax] parameters specify the range of the parent animation value that should be transformed. |
| 26 | + /// The [toMin] and [toMax] parameters specify the range to which the animation value should be transformed. |
| 27 | + /// |
| 28 | + /// The constructor asserts that [fromMin] is less than [fromMax] and [toMin] is less than [toMax]. |
| 29 | + const TransformedAnimation({ |
| 30 | + required this.parent, |
| 31 | + required this.fromMin, |
| 32 | + required this.fromMax, |
| 33 | + required this.toMin, |
| 34 | + required this.toMax, |
| 35 | + }) : assert(fromMin < fromMax, 'The fromMin value must be less than the fromMax value.'), |
| 36 | + assert(toMin < toMax, 'The toMin value must be less than the toMax value.'); |
| 37 | + |
| 38 | + /// The animation that this clamped animation is based on. |
| 39 | + @override |
| 40 | + final Animation<double> parent; |
| 41 | + |
| 42 | + /// The minimum value of the current range. |
| 43 | + final double fromMin; |
| 44 | + |
| 45 | + /// The maximum value of the current range. |
| 46 | + final double fromMax; |
| 47 | + |
| 48 | + /// The minimum value of the transformed range. |
| 49 | + final double toMin; |
| 50 | + |
| 51 | + /// The maximum value of the transformed range. |
| 52 | + final double toMax; |
| 53 | + |
| 54 | + /// Gets the current value of the parent animation transformed from the range [fromMin] -> [toMax] to [toMin] -> [toMax]. |
| 55 | + @override |
| 56 | + double get value { |
| 57 | + return (parent.value - fromMin) / (fromMax - fromMin) * (toMax - toMin) + toMin; |
| 58 | + } |
| 59 | + |
| 60 | + @override |
| 61 | + String toString() => 'TransformedAnimation(min: $toMin, max: $toMax)'; |
| 62 | +} |
0 commit comments