您的位置:首页 > 移动开发 > Android开发

用自定义继承Animation写一个跑圈运动

2015-10-27 23:18 351 查看
写一个继承Animation的类,我们定义为MyAnimation就行

MyAnimation:

public class MyAnimation extends Animation {

private int totalScrollX, totalScrollY; // 偏移量

public MyAnimation(int totalScrollX, int totalScrollY) {
this.totalScrollX = totalScrollX;
this.totalScrollY = totalScrollY;
}

//重写applyTransformation方法

protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
animationCircle(t, interpolatedTime);
}

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();
}

}

MainActivity:

public class MainActivity extends Activity {

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;
}
};

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 动画 继承