如何连续旋转一张图片?

17

我正在尝试使用线程旋转这张图片。我应该怎么做?

public class Start extends Activity {
    View base;
    Bitmap rotate, base1, rotate1;
    ImageView rotator;
    float angle, pivX, pivY;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start);
        base = findViewById(R.id.base);
        rotator = (ImageView) findViewById(R.id.rotator);
        pivX = (rotator.getLeft()) / 2;
        pivY = (rotator.getTop()) / 2;
    
        Thread thread = new Thread() {
            @Override
            public void run() {
                for (angle = 0; angle < 50; angle++) {
                    Matrix matrix = new Matrix();
                    rotator.setScaleType(ScaleType.MATRIX); // required
                    matrix.postRotate((float) angle, pivX, pivY);
                    rotator.setImageMatrix(matrix);
                    if (angle == 40) {`enter code here`
                        angle = 0;
                        return;
                    }
                }   
            }
        };
        
        thread.start();
    }
}

添加操作多次失败,已经厌倦了这个提示信息,请再添加一些文本。 - user2152295
只需尝试在视图上传递动画。试试我的帖子。只需复制粘贴代码并按照说明操作,就可以更好地理解。 - AndroidHacker
7个回答

34

使用此代码旋转按钮

btn_rotate = (Button)findViewById(R.id.btn_rotate);
rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
rotation.setFillAfter(true);
btn_rotate.startAnimation(rotation);

旋转.xml

将此文件放在res->anim->rotate.xml中。

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<rotate
    android:duration="500"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:startOffset="0"
    android:toDegrees="360" />
</set>

1
如果您希望仅使用Java代码来完成此操作,请告诉我,我会发布它。 - Rajan
1
如何停止这个动画。 - Prasad
你能发布一下吗?我只想用Java代码实现。@Rajan - abh22ishek
1
你也可以在xml中设置fillAfter属性:<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true"> - Daniil
4
但是每次轮播都会暂停这个动画。如何避免这种情况? - Evgeniy Pavlov
如果我多次旋转,就会出现加速和减速,看起来很丑。 - Jiří Křivánek

27

我知道可能有点晚了,但是这是我在Java代码中执行旋转动画的方法:

RotateAnimation rotate = new RotateAnimation(
                0, 360,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f
        );

rotate.setDuration(900);
rotate.setRepeatCount(Animation.INFINITE);
itemImage.startAnimation(rotate);

即使将持续时间设置为1500,也仍然不够流畅! - Jayesh Rathod

10

看这个..

你的Java类..

package com.example.rotate;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements AnimationListener {

    TextView txtMessage;
    Button btnStart;

    // Animation
    Animation animFadein;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtMessage = (TextView) findViewById(R.id.tv);
        btnStart = (Button) findViewById(R.id.btn);

        // load the animation
        animFadein = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.rotate);

        // set animation listener
        animFadein.setAnimationListener(this);

        // button click event
        btnStart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                txtMessage.setVisibility(View.VISIBLE);

                // start the animation
                txtMessage.startAnimation(animFadein);
            }
        });

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        // Take any action after completing the animation

        // check for fade in animation
        if (animation == animFadein) {
            Toast.makeText(getApplicationContext(), "Animation Stopped",
                    Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAnimationStart(Animation animation) {
        // TODO Auto-generated method stub

    }

}

你的XML文件..

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >


    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

还有一件事..你需要在res文件夹中定义anim文件夹。

现在将rotate.xml文件放在anim文件夹中。

rotate.xml文件

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="600"
        android:repeatMode="restart"
        android:repeatCount="infinite"
        android:interpolator="@android:anim/cycle_interpolator"/>

</set>

就这样了,你可以开始了。


1
@OmidOmidi 你可以通过改变 android:duration 的值来控制速度,值越高,速度越慢。 - Bhavik Mehta
2
我发现插值器需要放置在动画集中才能发挥作用。 - MCR

1

这个在使用Kotlin和Android API 29时对我有效:

val imageViewAnimator = ObjectAnimator.ofFloat(imageView,View.TRANSLATION_Y, 30f)
    imageViewAnimator.repeatCount = Animation.INFINITE
    imageViewAnimator.repeatMode = ObjectAnimator.REVERSE
    imageViewAnimator.duration = 1500
    imageViewAnimator.start()

这段代码的结果是一个“慢弹跳”的无限动画,但你可以使用ObjectAnimator属性自由修改它。

0

在 Kotlin 中:

 ivBall.setOnClickListener(View.OnClickListener {

            //Animate using XML
            // val rotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.rotate_indefinitely)

            //OR using Code
            val rotateAnimation = RotateAnimation(
                    0f, 359f,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f

            )
            rotateAnimation.duration = 300
            rotateAnimation.repeatCount = 2

            //Either way you can add Listener like this
            rotateAnimation.setAnimationListener(object : Animation.AnimationListener {

                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {

                    val rand = Random()
                    val ballHit = rand.nextInt(50) + 1
                    Toast.makeText(context, "ballHit : " + ballHit, Toast.LENGTH_SHORT).show()
                }
            })

            ivBall.startAnimation(rotateAnimation)
        })

rotate_indefinitely.xml

<?xml version="1.0" encoding="UTF-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="600"
    android:fromDegrees="0"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:toDegrees="360" />

0
ImageView img = findViewById(R.id.planet); img.animate().rotationBy(3000).setDuration(60000).setInterpolator(new LinearInterpolator()).start();

您的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认您的回答是否正确。您可以在帮助中心找到关于如何编写好回答的更多信息。 - Community

0
你可以在 Kotlin 中创建一个扩展:
fun ImageView.rotate(){
val rotateAnimation = RotateAnimation(
    0f, 359f,
    Animation.RELATIVE_TO_SELF, 0.5f,
    Animation.RELATIVE_TO_SELF, 0.5f

)
rotateAnimation.duration = 300
rotateAnimation.setAnimationListener(object : Animation.AnimationListener {
    override fun onAnimationStart(animation: Animation?) {}
    override fun onAnimationRepeat(animation: Animation?) {}
    override fun onAnimationEnd(animation: Animation?) {}
})
this.startAnimation(rotateAnimation)

}


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