自定义动画:重写父类的initialize完成初始化操作,实现applyTransformation逻辑
第一个例子:实现电视关闭时屏幕的关闭效果
public class CustomAnim extends Animation {
private int mCenterWidth;
private int mCenterHeight;
@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;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix=t.getMatrix();
matrix.preScale(1,1-interpolatedTime,mCenterWidth,mCenterHeight);
}
}
ImageView的点击事件
public void imgClose(View view) {
CustomAnim customTV = new CustomAnim();
view.startAnimation(customTV);
}
protected void applyTransformation(float interpolatedTime, Transformation t)
第一个参数就是插值器的时间因子 第二个参数是矩阵的封装类,用这个类获取当前的矩阵对象
第二个例子:利用Camera实现自定义的3D动画效果
public class CustomAnima 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(2000);
setFillAfter(true);
setInterpolator(new BounceInterpolator());
mCenterWidth=width/2;
mCenterHeight=height/2;
}
public void setRotateY(float rotatey){
this.mRotateY=rotatey;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix=t.getMatrix();
mCamera.save();
//使用camera旋转的角度
mCamera.rotateY(mRotateY*interpolatedTime);
mCamera.getMatrix(matrix);
mCamera.restore();
//通过pre方法设置矩阵作用前的偏移量来改变旋转中心
matrix.preTranslate(mCenterWidth,mCenterHeight);
matrix.postTranslate(-mCenterWidth,-mCenterHeight);
}
}
public void btnAnim(View view) {
CustomAnima customAnim = new CustomAnima();
customAnim.setRotateY(30);
view.startAnimation(customAnim);
}