lerp.dart 1.6 KB
Newer Older
M
Michael Goderbauer 已提交
1
// Copyright 2013 The Flutter Authors. All rights reserved.
A
Adam Barth 已提交
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
// @dart = 2.10
6

A
Adam Barth 已提交
7
part of dart.ui;
A
Adam Barth 已提交
8

9 10 11 12 13 14
/// Linearly interpolate between two numbers, `a` and `b`, by an extrapolation
/// factor `t`.
///
/// When `a` and `b` are equal or both NaN, `a` is returned.  Otherwise, if
/// `a`, `b`, and `t` are required to be finite or null, and the result of `a +
/// (b - a) * t` is returned, where nulls are defaulted to 0.0.
15
double? lerpDouble(num? a, num? b, double t) {
16 17
  if (a == b || (a?.isNaN == true) && (b?.isNaN == true))
    return a?.toDouble();
18 19
  a ??= 0.0;
  b ??= 0.0;
20 21 22
  assert(a.isFinite, 'Cannot interpolate between finite and non-finite values');
  assert(b.isFinite, 'Cannot interpolate between finite and non-finite values');
  assert(t.isFinite, 't must be finite when interpolating between values');
23
  return a * (1.0 - t) + b * t as double;
A
Adam Barth 已提交
24
}
Y
Yegor 已提交
25 26 27 28

/// Linearly interpolate between two doubles.
///
/// Same as [lerpDouble] but specialized for non-null `double` type.
29
double _lerpDouble(double a, double b, double t) {
30
  return a * (1.0 - t) + b * t;
Y
Yegor 已提交
31 32 33 34 35
}

/// Linearly interpolate between two integers.
///
/// Same as [lerpDouble] but specialized for non-null `int` type.
36
double _lerpInt(int a, int b, double t) {
37
  return a * (1.0 - t) + b * t;
Y
Yegor 已提交
38 39 40
}

/// Same as [num.clamp] but specialized for non-null [int].
41
int _clampInt(int value, int min, int max) {
Y
Yegor 已提交
42 43 44 45 46 47 48 49 50
  assert(min <= max);
  if (value < min) {
    return min;
  } else if (value > max) {
    return max;
  } else {
    return value;
  }
}