自定義動畫
創建自定義動畫非常簡單,只需要實現它的applyTransformation的邏輯就可以了,不過通常情況下,還需要覆蓋父類的Initialize方法來實現一些初始化工作,
下面,通過實現一個電視機關機的動畫來看一下用法。
效果非常簡單,讓一個圖片縱向比例不斷縮小即可,對應的矩陣處理方法如下:
Matrix matrix = t.getMatrix();
matrix.preScale(1, 1-interpolatedTime,halfWidth,halfHeight);
其中,halfWidth 和 halfHeight即爲縮放的中心點,設置爲圖片中心即可,這樣通過一個簡單的矩陣變換,就可以模擬電視機關閉的動畫。
當然,還可以設置更加精確的插值器,並將0到1.0的時間因子拆分成不同的過程,從而對不同的過程採用不同的動畫效果,模擬更加真實的特效。
具體實現代碼如下:
首先是定義動畫類
TVOffAnimation
package com.example.administrator.myapplication;
import android.graphics.Matrix;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
/**
* Created by Administrator on 2015/11/26 0026.
*/
public class TVOffAnimation extends Animation {
private int halfWidth;
private int halfHeight;
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
setDuration(500);
setFillAfter(true);
//保存View的中心點
halfWidth = width / 2;
halfHeight = height / 2;
setInterpolator(new AccelerateDecelerateInterpolator());
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix = t.getMatrix();
if (interpolatedTime < 0.8) {
matrix.preScale(1+0.625f*interpolatedTime, 1-interpolatedTime/0.8f+0.01f,halfWidth,halfHeight);
}else{
matrix.preScale(7.5f*(1-interpolatedTime),0.01f,halfWidth,halfHeight);
}
}
}
然後,是Activity調用
MyTvAnimationActivity
package com.example.administrator.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Created by Administrator on 2015/11/26 0026.
*/
public class MyTvAnimationActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tvmain);
Button b = (Button) findViewById(R.id.Button01);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View img = findViewById(R.id.ImageView01);
img.startAnimation(new TVOffAnimation());
}
});
}
}
效果圖如下所示:
更多效果,就需要慢慢探索了。。。。