代码部分来自其他博客,如有侵权,请留言。
在编写Android按照Y轴翻转时遇到了问题,找不到合适的方法。所以记录下来。
package com.crescert.myapplication;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
/**
* 围绕Y轴翻转
*/
public class MyYAnimation extends Animation {
//中心点
int centerX, centerY;
Camera camera = new Camera();
//默认为反转360度
float Degress = 360;
//默认周期为3秒
long time = 3 * 1000;
MyYAnimation() {}
/**
* 翻转角度
* @param degress
*/
MyYAnimation(int degress) {
this.Degress = degress;
}
/**
* 翻转角度以及时间设置
* @param degress
* @param time
*/
MyYAnimation(int degress, long time) {
this(degress);
if (time != 0)
this.time = time;
}
/**
* 获取坐标,定义动画时间
*
* @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;
//动画执行时间 自行定义
setDuration(time);
setInterpolator(new DecelerateInterpolator());
}
/**
* 旋转的角度设置
*
* @param interpolatedTime
* @param t
*/
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix = t.getMatrix();
camera.save();
//中心是Y轴旋转,这里可以自行设置X轴 Y轴 Z轴
camera.rotateY(Degress * interpolatedTime);
//把我们的摄像头加在变换矩阵上
camera.getMatrix(matrix);
//设置翻转中心点
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
camera.restore();
}
}
MyYAnimation myYAnimation = new MyYAnimation();
myYAnimation.setRepeatCount(Animation.INFINITE);
wai.startAnimation(myYAnimation);
MyYAnimation myYAnimation1 = new MyYAnimation(-360,5000);
myYAnimation1.setRepeatCount(Animation.INFINITE);
nei.startAnimation(myYAnimation1);
即可实现按照Y轴翻转