如何在flutter中使用lerp()方法以及用例是什么?

时间:2020-05-19 11:42:11

标签: flutter

我实际上在许多Flutter动画中都遇到了lerp函数。我研究了线性插值。但是我不知道它如何在颤动中使用以及用例是什么。有人可以解释吗?

2 个答案:

答案 0 :(得分:5)

它在两个值之间线性插值,例如:

var color = Color.lerp(Colors.white, Colors.black, 0.5);
var value = lerpDouble(10, 20, 0.5); // 15

此处的color的中间值介于白色和黑色之间。

答案 1 :(得分:4)

您还可以使用它在标签视图上拖动时为颜色设置动画。

btn

var unselectedColor = Theme.of(context).unselectedWidgetColor;
var selectedColor = Theme.of(context).primaryColor;

Color color;

bool isSelected = itemIndex == tabController.index;
int currentIndex = tabController.index;

double offset = tabController.offset;

bool dragToRight = offset > 0;

if (dragToRight) {
  if (itemIndex >= currentIndex && itemIndex <= currentIndex + 1) {
    color = isSelected
        ? Color.lerp(selectedColor, unselectedColor, offset)
        : Color.lerp(unselectedColor, selectedColor, offset);
  }
} else {
  if (itemIndex >= currentIndex - 1 && itemIndex <= currentIndex) {
    color = isSelected
        ? Color.lerp(selectedColor, unselectedColor, -offset)
        : Color.lerp(unselectedColor, selectedColor, -offset);
  }
}