lerp static method
Linearly interpolate between two colors.
This is intended to be fast but as a result may be ugly. Consider HSVColor or writing custom logic for interpolating colors.
If either color is null, this function linearly interpolates from a
transparent instance of the other color. This is usually preferable to
interpolating from material.Colors.transparent (const Color(0x00000000)), which is specifically transparent black.
The t argument represents position on the timeline, with 0.0 meaning
that the interpolation has not started, returning a (or something
equivalent to a), 1.0 meaning that the interpolation has finished,
returning b (or something equivalent to b), and values in between
meaning that the interpolation is at the relevant point on the timeline
between a and b. The interpolation can be extrapolated beyond 0.0 and
1.0, so negative values and values greater than 1.0 are valid (and can
easily be generated by curves such as Curves.elasticInOut). Each channel
will be clamped to the range 0 to 255.
Values for t are usually obtained from an Animation<double>, such as
an AnimationController.
If the two colors are in different color spaces, both are converted to the wider gamut color space before interpolating. The result will be in the wider gamut color space. For example, interpolating between an sRGB color and a Display P3 color will produce a Display P3 result.
Implementation
static Color? lerp(Color? x, Color? y, double t) {
assert(x?.colorSpace != ColorSpace.extendedSRGB);
assert(y?.colorSpace != ColorSpace.extendedSRGB);
if (y == null) {
if (x == null) {
return null;
} else {
return _scaleAlpha(x, 1.0 - t);
}
} else {
if (x == null) {
return _scaleAlpha(y, t);
} else {
final Color a;
final Color b;
final ColorSpace resultColorSpace;
if (x.colorSpace == y.colorSpace) {
a = x;
b = y;
resultColorSpace = x.colorSpace;
} else {
resultColorSpace = _widerColorSpace(x.colorSpace, y.colorSpace);
a = x.withValues(colorSpace: resultColorSpace);
b = y.withValues(colorSpace: resultColorSpace);
}
return Color.from(
alpha: clampDouble(_lerpDouble(a.a, b.a, t), 0, 1),
red: clampDouble(_lerpDouble(a.r, b.r, t), 0, 1),
green: clampDouble(_lerpDouble(a.g, b.g, t), 0, 1),
blue: clampDouble(_lerpDouble(a.b, b.b, t), 0, 1),
colorSpace: resultColorSpace,
);
}
}
}