如何以编程方式执行RotateAnimations的完整示例?

Hei*_*upp 12 animation android

我希望有一个动画,其中包含各种步骤,可以移动(翻译)和旋转,例如汽车的"直行,左转,直行,......".

我可以在一个中执行此操作AnimationSet,但无法使用"RELATIVE_TO_SELF"设置围绕我的汽车图像中心旋转.我知道

Animation a = new RotateAnimation(0,90,Animation.RELATIVE_TO_SELF,0.5f,... )
Run Code Online (Sandbox Code Playgroud)

以此目的.旋转仍然发生在屏幕左上角(或画布?)周围.

目前我通过在每个动画步骤之后手动跟踪位置来解决这个问题,但这不是最理想的.

我怀疑我的初始布局设置是假的:

<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>
Run Code Online (Sandbox Code Playgroud)

这显示了左上角的汽车(应该显示在不同的地方 - 基本上是动画后来开始的地方.它应该稍后移动).

在我通过运行按钮触发的代码中,我执行以下操作:

    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);
    ...
Run Code Online (Sandbox Code Playgroud)

所以在这里,旋转工作,但我必须跟踪.如果我旋转RELATIVE_TO_SELF,旋转发生在屏幕的(0,0)左右.

附加问题:为了在动画结束后将汽车保持在屏幕上,我该怎么办?

还是我完全走错了路?

and*_*oot 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);
...
Run Code Online (Sandbox Code Playgroud)

  • 注意:这里的最后一步是调用`carView.startAnimation(animationSet);` (13认同)