一個LinearLayout有一張背景圖片,裡面有一個ImageButton子組件,子組件完成360度順時針旋轉效果。
MainActivity:
我只是啟動Activity就顯示動畫效果,所以在oncreate()方法中類比,但是這時候imageButton尺寸大小的值不太容易擷取,我上一篇文章已經講到了這個問題。
oncreate中擷取組件尺寸大小: http://blog.csdn.net/u010152805/article/details/17592083
public class MainActivity extends Activity {private ImageButton ib;float w,y;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); //在oncreate()中擷取imageButton尺寸大小 ViewTreeObserver vto = ib.getViewTreeObserver();vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {ib.getViewTreeObserver().removeGlobalOnLayoutListener(this);w=ib.getWidth();y=ib.getHeight();rotateAnim(w,y);}});}/** * 實現動畫旋轉效果 */private void rotateAnim(float w,float y) {//圖片旋轉中心座標final float centerX = w/ 2.0f;final float centerY = y/ 2.0f;RotateAnimation rotation; rotation = new RotateAnimation(0, -360, centerX, centerY, 310.0f, false);rotation.setDuration(1500);//動畫期間rotation.setFillAfter(true);rotation.setInterpolator(new DecelerateInterpolator());//設定加速度rotation.setRepeatCount(Animation.INFINITE);//重複次數rotation.setRepeatMode(Animation.RESTART);//重複動畫ib.startAnimation(rotation);}}動畫類:
/** * 3D動畫效果類 * 三個關鍵類 (Animation/Camera/Matrix) */public class RotateAnimation extends Animation {/**開始角度*/private final float mFromDegrees;/**結束角度*/private final float mToDegrees;/**中心座標X軸*/private final float mCenterX;/**中心座標Y軸*/private final float mCenterY;/**反面*/private final boolean mReverse;/**相機類*/private Camera mCamera;/** * 構造方法 * @param fromDegrees 開始角度 * @param toDegrees 結束角度 * @param centerX 中心座標 * @param centerY 中心座標 * @param depthZ * @param reverse */public RotateAnimation(float fromDegrees, float toDegrees,float centerX, float centerY, float depthZ, boolean reverse) {mFromDegrees = fromDegrees;mToDegrees = toDegrees;mCenterX = centerX;mCenterY = centerY;mReverse = reverse;}/** * 初始化動畫對象尺寸 */@Overridepublic void initialize(int width, int height, int parentWidth,int parentHeight) {super.initialize(width, height, parentWidth, parentHeight);mCamera = new Camera();}@Overrideprotected void applyTransformation(float interpolatedTime, Transformation tran) {final float fromDegrees = mFromDegrees;float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);final float centerX = mCenterX;final float centerY = mCenterY;final Camera camera = mCamera;final Matrix matrix = tran.getMatrix();camera.save();//儲存狀態if (mReverse) {//x,y,z距離中心軸各自的距離長度camera.translate(0.0f, 0.0f, 0.0f); } else {camera.translate(0.0f, 0.0f, 0.0f);}//以多少角度圍繞Y軸旋轉,可以圍繞X,Y,Z三個方向旋轉camera.rotateY(degrees);camera.getMatrix(matrix);//恢複儲存狀態camera.restore();matrix.preTranslate(-centerX, -centerY);matrix.postTranslate(centerX, centerY);}}