MainActivity :
private ImageView iv_circle;
private int totalX;
private int totalY;
private MyAnimation animation;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_circle = (ImageView) findViewById(R.id.iv_circle);
}
public void startAnimation(View view) {
totalX = 200;
totalY = 100;
animation = new MyAnimation(totalX, totalY);
animation.setDuration(2000);
animation.setFillAfter(true);
animation.setOnAnimationAfterListener(listener);
iv_circle.startAnimation(animation);
}
private OnAnimationAfterListener listener = new OnAnimationAfterListener() {
public void onAnimationAfter() {
if (animation != null) {
animation.cancel();
animation = null;
}
animation = new MyAnimation(-totalX, -totalY);
animation.setDuration(2000);
animation.setFillAfter(true);
animation.setOnAnimationAfterListener(listener);
iv_circle.startAnimation(animation);
totalX = -totalX;
totalY = -totalY;
}
};
}
MyAnimation :
public class MyAnimation extends Animation {
private int totalScrollX, totalScrollY; // 偏移量
/**
* @param totalScrollX
* 偏移量X
* @param totalScrollY
* 偏移量Y
*/
public MyAnimation(int totalScrollX, int totalScrollY) {
this.totalScrollX = totalScrollX;
this.totalScrollY = totalScrollY;
}
//从写applyTransformation方法
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
// animationSin(t, interpolatedTime); //设置正弦运动
animationCircle(t, interpolatedTime); //设置跑圈运动
}
//设置后是正弦曲线运动
public void animationSin(Transformation t, float interpolatedTime) {
float currentScrollX = totalScrollX * interpolatedTime;
float currentScrollY = (float) (totalScrollY * Math.sin(2 * Math.PI
* interpolatedTime));
t.getMatrix().setTranslate(currentScrollX, currentScrollY);
}
//设置后是圆圈运动
public void animationCircle(Transformation t, float interpolatedTime) {
float currentScrollX = 0;
float currentScrollY = 0;
if (totalScrollX > 0) {
currentScrollX = totalScrollX * interpolatedTime;
} else {
currentScrollX = Math.abs(totalScrollX) * (1-interpolatedTime);
}
if (totalScrollY > 0) {
currentScrollY = (float) Math.sqrt(Math.pow(totalScrollY, 2)
- Math.pow(currentScrollX - Math.abs(totalScrollY), 2));
} else {
currentScrollY = -(float) Math.sqrt(Math.pow(totalScrollY, 2)
- Math.pow(currentScrollX - Math.abs(totalScrollY), 2));
}
t.getMatrix().setTranslate(currentScrollX, currentScrollY);
if (listener != null && interpolatedTime == 1.0) {
if (isFinish) {
return;
}
isFinish = true;
listener.onAnimationAfter();
}
}
private OnAnimationAfterListener listener;
private boolean isFinish = false;
public void setOnAnimationAfterListener(OnAnimationAfterListener listener) {
this.listener = listener;
}
public interface OnAnimationAfterListener {
public void onAnimationAfter();
}
}