简体   繁体   English

如何为 Android 动画 (Kotlin) 制作自定义插值器?

[英]How to make a custom interpolator for Android animation (Kotlin)?

Loosely, this is my code, boiled down to the relevant parts:松散地,这是我的代码,归结为相关部分:

fun animate(tv: TextView) {
    var animationSlide = TranslateAnimation(0.0f, 0.0f, 100.0f, 0f)
    var animationScale = ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f)
    animationSlide.interpolator = AccelerateInterpolator() // want custom interpolator
    animationScale.interpolator = DecelerateInterpolator() // want custom interpolator
    animationSlide.duration = 1000
    animationScale.duration = 1000
    var animationSet = AnimationSet(false)
    animationSet.addAnimation(animationSlide)
    animationSet.addAnimation(animationScale)
    tv.startAnimation(animationSet)
}

Is it possible to make a custom interpolator which takes an array of points, or a lambda function which takes a time input and returns a value for that time point?是否可以制作一个接受点数组的自定义插值器,或者一个接受时间输入并返回该时间点值的 lambda 函数? The Android documentation only shows a small list of interpolators, none of which can be customised to a general function curve. Android 文档只显示了一小部分插值器,其中没有一个可以自定义为通用函数曲线。

Thanks for any help!谢谢你的帮助!

This is done by making a class that implements Interpolator.这是通过创建一个实现 Interpolator 的类来完成的。 Or you can use a SAM-converted lambda.或者您可以使用 SAM 转换的 lambda。 For example, an interpolation based on the smoothstep function:例如,基于smoothstep函数的插值:

animationSlide.setInterpolator { amount ->
    amount * amount * (3f - 2f * amount)
}

If you want to define a set of points to define your curve, you can do that with the Path class and instantiate a PathInterpolator with that.如果你想定义一组点来定义你的曲线,你可以用 Path 类来做,并用它实例化一个 PathInterpolator。 From looking at the source code, it looks like PathInterpolator approximates the Path by breaking it down into straight line segments, so if there are arcs and Beziers, it could potentially become kind of a heavy class instance that you might want to cache a reference to if you use it repeatedly.从查看源代码来看,看起来 PathInterpolator 通过将路径分解为直线段来近似路径,因此如果有弧线和贝塞尔曲线,它可能会成为您可能想要缓存引用的重类实例如果你反复使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM