1. 程式人生 > >android 翻轉效果動畫原始碼

android 翻轉效果動畫原始碼

     最近專案上要求做一個翻轉的動畫效果,由於動畫還沒有怎麼使用過。然後再網上找到一份很實用的翻轉動畫先用起來,以後再學習下動畫相關的。

原始碼修改後如下:

    public class FlipAnimator extends Animation {

        private Camera camera;

        private float centerX;

        private float centerY;

        public FlipAnimator() {
            setFillAfter(true);
        }


        @Override
        public void initialize(int width, int height, int parentWidth, int parentHeight) {
            super.initialize(width, height, parentWidth, parentHeight);
            camera = new Camera();
            this.centerX = width / 2;
            this.centerY = height / 2;
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            // Angle around the y-axis of the rotation at the given time. It is
            // calculated both in radians and in the equivalent degrees.
            final double radians = Math.PI * interpolatedTime;
            float degrees = (float) (180.0 * radians / Math.PI);

            degrees = -degrees;

            // Once we reach the midpoint in the animation, we need to hide the
            // source view and show the destination view. We also need to change
            // the angle by 180 degrees so that the destination does not come in
            // flipped around. This is the main problem with SDK sample, it does not
            // do this.
            if (interpolatedTime >= 0.5f) {
                degrees += 180.f;
            }

            final Matrix matrix = t.getMatrix();

            camera.save();
            camera.translate(0.0f, 0.0f, (float) (150.0 * Math.sin(radians)));
//            camera.rotateX(degrees);
            camera.rotateY(degrees);
//            camera.rotateZ(degrees);
            camera.getMatrix(matrix);
            camera.restore();

            matrix.preTranslate(-centerX, -centerY);
            matrix.postTranslate(centerX, centerY);
        }
    }

        動畫通過Camera 和Matrix實現。文中注視的部分camera.rotateX(degrees)和camera.rotateZ(degrees)分別為X和Z軸的旋轉,沒有用到故先註釋。

        使用方法很簡單

                FlipAnimator flipAnimator = new FlipAnimator();
                flipAnimator.setDuration(200);
                startAnimation(flipAnimator);