创建自定义动画非常简单,只要实现他的applyTransformation的逻辑就可以了,不过通常情况下还要覆盖父类的initialize方法来实现一些初始化工作。
模拟电视机关闭效果动画
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class CustomTV extends Animation {
private int mCenterWidth;
private int mCenterHeight;
private Camera mCamera = new Camera();
private float mRotateY = 0.0f;
@Override
public void initialize(int width,
int height,
int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
// 设置默认时长
setDuration(1000);
// 动画结束后保留状态
setFillAfter(true);
// 设置默认插值器
setInterpolator(new AccelerateInterpolator());
mCenterWidth = width / 2;
mCenterHeight = height / 2;
}
// 暴露接口-设置旋转角度
public void setRotateY(float rorateY) {
mRotateY = rorateY;
}
@Override
protected void applyTransformation(
float interpolatedTime,
Transformation t) {
final Matrix matrix = t.getMatrix();
matrix.preScale(1,
1 - interpolatedTime,
mCenterWidth,
mCenterHeight);
}
}
关于Interpolator 时间插值类,定义动画变换的速度。能够实现alpha/scale/translate/rotate动画的加速、减速和重复等。Interpolator类其实是一个空接口,继承自TimeInterpolator,TimeInterpolator时间插值器允许动画进行非线性运动变换,如加速和限速等,该接口中只有接口中有一个方法 float getInterpolation(float input)这个方法。传入的值是一个0.0~1.0的值,返回值可以小于0.0也可以大于1.0。
AccelerateDecelerateInterpolator 动画开始与结束的地方速率改变比较慢,在中间的时候加速。
AccelerateInterpolator 动画开始的地方速率改变比较慢,然后开始加速。
AnticipateInterpolator 开始的时候向后然后向前甩。
AnticipateOvershootInterpolator 开始的时候向后然后向前甩一定值后返回最后的值。
BounceInterpolator 动画结束的时候弹起。
CycleInterpolator 动画循环播放特定的次数,速率改变沿着正弦曲线。
DecelerateInterpolator 在动画开始的地方快然后慢。
LinearInterpolator 以常量速率改变。
OvershootInterpolator 向前甩一定值后再回到原来位置。
PathInterpolator 新增的,就是可以定义路径坐标,然后可以按照路径坐标来跑动;注意其坐标并不是 XY,而是单方向,也就是我可以从0~1,然后弹回0.5 然后又弹到0.7 有到0.3,直到最后时间结束。