在代码中继承android.view.animation.Animation类来实现自定义效果。通过重写Animation的applyTransformation(float interpolatedTime, Transformation t)函数来实现自定义动画效果
在绘制动画的过程中会反复的调用applyTransformation函数,每次调用参数interpolatedTime值都会变化,该参数从0渐 变为1,当该参数为1时表明动画结束。通过参数Transformation 来获取变换的矩阵(matrix),通过改变矩阵就可以实现各种复杂的效果。
下面实现一个对角展开的动画效果
继承Animation的子类:
package com.demo;
import android.graphics.Matrix;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
/**
* @author symbol
*/
public class CustomAnimation extends Animation {
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
setDuration(500);
setFillAfter(false);
setInterpolator(new AccelerateDecelerateInterpolator());
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix = t.getMatrix();
// if (interpolatedTime < 0.8) {
matrix.preScale(interpolatedTime, interpolatedTime,0,0);//对象展开动画
// }else{
// matrix.preScale(7.5f*(1-interpolatedTime),0.01f,halfWidth,halfHeight);
// }
}
}
Activity类:
package com.demo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.Button01);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
View img = findViewById(R.id.ImageView01);
img.startAnimation(new CustomAnimation());
}
});
}
}
xml布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/ImageView01" android:src="@drawable/psb"
android:layout_width="wrap_content" android:layout_height="wrap_content">
</ImageView>
<Button android:text="点击" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/Button01"
android:layout_alignParentBottom="true"></Button>
</RelativeLayout>