有很多地方要用到旋转动画,而且方法也不少,这里介绍的是利用Camera和Matrix来实现的。
废话不多说,先上代码:
public class RotateYAnimation extends Animation {
int centerX, centerY;
Camera camera = new Camera();
/**
* 获取坐标,定义动画时间
* @param width
* @param height
* @param parentWidth
* @param parentHeight
*/
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
//获得中心点坐标
centerX = width / 2;
centerY = width / 2;
//动画执行时间 自行定义
setInterpolator(new OvershootInterpolator());
}
/**
* 旋转的角度设置
* @param interpolatedTime
* @param t
*/
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix = t.getMatrix();
camera.save();
//设置camera的位置
camera.setLocation(0,0,180);
camera.rotateY(180 * interpolatedTime);
//把我们的摄像头加在变换矩阵上
camera.getMatrix(matrix);
//设置翻转中心点
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX,centerY);
camera.restore();
}
}
这是一个旋转动画类,里面的camera类是
android.graphics.Camera;
将RotateYAnimation类,添加到我们要进行的动画控件上:
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
RotateYAnimation animation = new RotateYAnimation();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.iv);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//旋转的次数
animation.setRepeatCount(0);
//旋转的时间
animation.setDuration(1000);
//是否停留在动画的最后一帧
animation.setFillAfter(true);
imageView.startAnimation(animation);
}
});
}
}
最后效果如图: