如何为Android准备曲线平移动画?

12
在安卓中有四种类型的动画 - 旋转、透明度、缩放和位移。我想准备一种曲线位移动画,这个可行吗?
3个回答

10
你正在使用哪个Android版本?自API 11起,你可以使用自定义Animators,它可以轻松实现你的曲线平移。
如果你使用的是比这更低版本的Android系统,那么只有手动连接多个线性平移才能实现平移动画,并设置动画监听器。
编辑:
示例:
View view;
animator = ValueAnimator.ofFloat(0, 1); // values from 0 to 1
animator.setDuration(5000); // 5 seconds duration from 0 to 1
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
{
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float value = ((Float) (animation.getAnimatedValue()))
                    .floatValue();
        // Set translation of your view here. Position can be calculated
        // out of value. This code should move the view in a half circle.
        view.setTranslationX((float)(200.0 * Math.sin(value*Math.PI)));
        view.setTranslationY((float)(200.0 * Math.cos(value*Math.PI)));
    }
});

希望它能正常工作。我只是从我的一个应用程序中复制并粘贴了代码(并进行了缩短和更改)。


请提供在Android 3.0中准备曲线翻译的一些示例代码。 - user884126
先生,我能否使用nine-old-android库在API级别低于11的情况下实现曲线动画? - Rat-a-tat-a-tat Ratatouille

4

这里是我使用的动画制作工具:

目的:在路径“path”上移动视图“view”

适用于Android v21+版本:

// Animates view changing x, y along path co-ordinates
ValueAnimator pathAnimator = ObjectAnimator.ofFloat(view, "x", "y", path)

Android v11+:

// Animates a float value from 0 to 1 
ValueAnimator pathAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);

// This listener onAnimationUpdate will be called during every step in the animation
// Gets called every millisecond in my observation  
pathAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

float[] point = new float[2];

@Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // Gets the animated float fraction
        float val = animation.getAnimatedFraction();

        // Gets the point at the fractional path length  
        PathMeasure pathMeasure = new PathMeasure(path, true);
        pathMeasure.getPosTan(pathMeasure.getLength() * val, point, null);

        // Sets view location to the above point
        view.setX(point[0]);
        view.setY(point[1]);
    }
});

与之类似:Android如何使位图沿着路径移动?


1
花更多的时间解释你的答案是有帮助的,这样提问者就可以更容易地跟随你的代码。 - SuperBiasedMan
1
@SuperBiasedMan 感谢您的反馈!已在注释中添加了解释。 - Dileep P G
我不得不执行 pathMeasure.getLength()/2,因为视图总是返回到它的原始位置。 - Rick
1
视图可能会返回到其原始位置,因为您将true传递给了PathMeasure(path,forceClose)。这告诉它关闭路径,从最后一个点添加一条线到原始位置。 - dephinera

-1

3
虽然这个回答理论上可以回答问题,但更好的做法是(http://meta.stackexchange.com/q/8259)您编辑回答以包括解决方案的关键部分,并提供参考链接。 - Peter O.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接