我只是想实现一个简单的3D旋转动画而已,但是在网上看了那么多都是很繁琐,找了半天才找到自己要用的那部分代码。直接抽取出来:
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Camera;
import android.graphics.Matrix;
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("3D Rotate");
Rotate3d rotate = new Rotate3d();
rotate.setDuration(1000);
tv.startAnimation(rotate);
setContentView(tv);
}
}
class Rotate3d extends Animation {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
Matrix matrix = t.getMatrix();
Camera camera = new Camera();
camera.save();
// 设置camera动作为绕Y轴旋转
// 总共旋转180度,因此计算在每个补间时间点interpolatedTime的角度即为两着相乘
camera.rotateY(180 * interpolatedTime);
// 根据camera动作产生一个matrix,赋给Transformation的matrix,以用来设置动画效果
camera.getMatrix(matrix);
camera.restore();
}
}
上述动画会转出屏幕,这时就需要对动画进行参数设置了
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Camera;
import android.graphics.Matrix;
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("3D Rotate");
Rotate3d rotate = new Rotate3d();
rotate.setDuration(1000);
tv.measure(0, 0);
rotate.setCenter(tv.getMeasuredWidth() / 2, tv.getMeasuredHeight() / 2);
rotate.setFillAfter(true); // 使动画结束后定在最终画面,如果不设置为true,则将会回到初始画面
tv.startAnimation(rotate);
setContentView(tv);
}
}
class Rotate3d extends Animation {
private float mCenterX = 0;
private float mCenterY = 0;
public void setCenter(float centerX, float centerY) {
mCenterX = centerX;
mCenterY = centerY;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
Matrix matrix = t.getMatrix();
Camera camera = new Camera();
camera.save();
camera.rotateY(180 * interpolatedTime);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-mCenterX, -mCenterY);
matrix.postTranslate(mCenterX, mCenterY);
}
}