直接上代碼
public class MyAnimation extends Animation {private int halfWidth;private int halfHeight;@Overridepublic void initialize(int width, int height, int parentWidth,int parentHeight) {// TODO Auto-generated method stubsuper.initialize(width, height, parentWidth, parentHeight);halfWidth = width / 2;halfHeight = height / 2;setDuration(3000);setInterpolator(new LinearInterpolator());}@Overrideprotected void applyTransformation(float interpolatedTime, Transformation t) {// TODO Auto-generated method stub//super.applyTransformation(interpolatedTime, t);final Matrix matrix = t.getMatrix();Matrix matrix2 = new Matrix();matrix2.setSinCos((float)Math.sin(interpolatedTime*30), 1f, (float)halfWidth, (float)halfHeight);matrix.preConcat(matrix2);}}
設計一個Animation的子類,然後重載了二個方法,其中applyTransformation方法是一個回調方法,在動畫進行的過程中,系統會一直不停的調用這個方法
註:當把setSinCos方法的第二個參數“1f ”換成其它數比如0.5f,5f 時,你會有意想不到的發現。第一個參數中的30能改變擺動的頻率
講setSinCos方法之前,先插點別的話。關於矩陣旋轉知識
其實setSinCos這個方法就是用來設定這個矩陣中的sin以及cos參數來實現對旋轉角度的控制
Activity中的代碼
button.setOnClickListener(new Button.OnClickListener(){public void onClick(View v) {// TODO Auto-generated method stubButton button1 = (Button)findViewById(R.id.button2);button1.startAnimation(new MyAnimation());} });