编程实现旋转动画的完整示例是什么?

12
我想要一个具有各种步骤的动画,其中包括汽车的移动(平移)和旋转,例如“直行,向左转,直行,...”。
我能够在一个AnimationSet中实现这一点,但是无法使用"RELATIVE_TO_SELF"设置以围绕汽车图像的中心旋转。我知道相关的方法:
Animation a = new RotateAnimation(0,90,Animation.RELATIVE_TO_SELF,0.5f,... )
为此目的,我仍然需要对屏幕(或画布?)的左上角进行旋转。目前我通过在每次动画步骤后手动跟踪位置来解决这个问题,但这是不太理想的。我怀疑我的初始布局设置是错误的:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical"
>
    <FrameLayout
            android:layout_height="wrap_content"
            android:layout_width="fill_parent">

        <!-- view that draws some background -->
        <de.bsd.turtlecar.SampleView android:id="@+id/graph_view"
              android:layout_height="350px"
              android:layout_width="fill_parent"
              android:visibility="invisible"
              />

        <!-- the car -->
        <ImageView android:id="@+id/car_view"
                   android:src="@drawable/turtle_car"
                   android:layout_height="wrap_content"
                   android:layout_width="wrap_content"
                   android:visibility="invisible"/>


    </FrameLayout>

   <Button ... onClick="run" ... />
</LinearLayout>

这显示了车辆在左上角(应该出现在其他位置 - 基本上是动画后来开始的地方。并且它应该稍后移动)。

在我的代码中,通过运行按钮触发:

    ImageView carView = (ImageView) findViewById(R.id.car_view);
    print(carView);
    AnimationSet animationSet = new AnimationSet(true);

    TranslateAnimation a = new TranslateAnimation(
            Animation.ABSOLUTE,200, Animation.ABSOLUTE,200,
            Animation.ABSOLUTE,200, Animation.ABSOLUTE,200);
    a.setDuration(1000);
    animationSet.addAnimation(a);

    RotateAnimation r = new RotateAnimation(0f, -90f,200,200); // HERE 
    r.setStartOffset(1000);
    r.setDuration(1000);
    animationSet.addAnimation(r);
    ...

所以在这个位置,旋转是有效的,但我必须要跟踪。如果我使用RELATIVE_TO_SELF进行旋转,则旋转会围绕屏幕的(0,0)进行。

另外一个问题:在动画完成后,我该怎么做才能让汽车保持在屏幕上?

或者我完全走错了吗?

1个回答

19

尝试在您的动画中添加setFillAfter(true)。这将确保汽车停留在最终位置,并可能解决旋转点的问题。


 TranslateAnimation a = new TranslateAnimation(
        Animation.ABSOLUTE,200, Animation.ABSOLUTE,200,
        Animation.ABSOLUTE,200, Animation.ABSOLUTE,200);
a.setDuration(1000);
a.setFillAfter(true); //HERE
animationSet.addAnimation(a);

RotateAnimation r = new RotateAnimation(0f, -90f,200,200); // HERE 
r.setStartOffset(1000);
r.setDuration(1000);
r.setFillAfter(true); //HERE
animationSet.addAnimation(r);
...

14
注意:这里的最后一步是调用 carView.startAnimation(animationSet); - Nilzor

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