Android只提供了4种基本动画效果,除了可以叠加效果外,我们还可以进行自定义动画。
- 制作一个随X/Y轴不断变化的平移动画效果
- 制作一个左右摇晃的动画效果
package com.customanim.customanim;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private CustomAnim ca;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ca = new CustomAnim();
ca.setDuration(1000);
findViewById(R.id.btnAnimMe).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
arg0.startAnimation(ca);
}
});
}
}
一、平移动画效果:
package com.customanim.customanim;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class CustomAnim extends Animation {
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
@Override
protected void applyTransformation(
float interpolatedTime//0-1s时间
, Transformation t//变化对象
) {
t.getMatrix().setTranslate(200*interpolatedTime,//沿X轴变化 200*interpolatedTime//沿Y轴变化 );
super.applyTransformation(interpolatedTime, t);
}
}
二、摇晃动画效果:
package com.customanim.customanim;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class CustomAnim extends Animation {
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
@Override
protected void applyTransformation(
float interpolatedTime//0-1s时间
, Transformation t//变化对象
) {
/*
*
Special cases:
sin(+0.0) = +0.0
sin(-0.0) = -0.0
sin(+infinity) = NaN
sin(-infinity) = NaN
sin(NaN) = NaN
参数:
d the angle whose sin has to be computed, in radians.
返回:
the sine of the argument.
*/
t.getMatrix().setTranslate((float) (Math.sin(interpolatedTime*20//控制摇晃的时间/频率)*50//控制摇晃的距离), 0);
super.applyTransformation(interpolatedTime, t);
}
}
Android自定义平移与摇晃动画
Android原生提供四种基本动画,但可通过自定义实现更复杂的动画效果。本文详细介绍了如何创建沿X/Y轴平移的动画,以及实现物体左右摇晃的动画效果,扩展了Android动画的应用。
830

被折叠的 条评论
为什么被折叠?



