Android實現dialog的3D翻轉

本文實現了Android中dialog的3D翻轉效果。這裏經過一個簡單的應用場景記錄下。android

效果圖

這裏寫圖片描述

起初本身的思路是Activity進行界面跳轉實現旋轉效果,網上看了不少,寫下來發現效果不對。以後又看到Google上面的Card Flid Animation效果是這樣的。app

這裏寫圖片描述

看着確實不錯,然而拿下來demo放慢翻轉速度後發現,不是我想要的。可是跟我看到的一個app裏面的效果同樣
而後想改爲dialog試試效果,發現更是不行了。ide

Card Flid Animation效果以下:
這個是經過Activity來切換Fragment實現的,能夠看到區別是翻轉時候貌似會變大,其實沒用,只是翻轉後的視覺問題。post

這裏寫圖片描述

據說openGl比較麻煩,而且沒有用過。而後就搜了下Rotate3DAnimaitons。動畫

搜到了這篇文章
http://blog.csdn.net/growing_...
因此這篇文章裏的實現方法不是個人原創,是參考人家的。在這裏感謝這位大神。
不過他這個是activity裏的,我就想要一個dialog效果,由於電腦上TIM的打開紅包這個3D效果看着不錯,其實大同小異,就拿過來改爲Dialog。
對於Rotate3DAnimaitons這篇文章已經很詳細了,有須要的能夠參考下。this

這裏也貼下Rotate3dAnimation 的代碼

簡單加了兩行註釋spa

/**
 * An animation that rotates the view on the Y axis between two specified angles.
 * This animation also adds a translation on the Z axis (depth) to improve the effect.
 */
public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

    /**
     * Creates a new 3D rotation on the Y axis. The rotation is defined by its
     * start angle and its end angle. Both angles are in degrees. The rotation
     * is performed around a center point on the 2D space, definied by a pair
     * of X and Y coordinates, called centerX and centerY. When the animation
     * starts, a translation on the Z axis (depth) is performed. The length
     * of the translation can be specified, as well as whether the translation
     * should be reversed in time.
     *
     * @param fromDegrees the start angle of the 3D rotation //起始角度
     * @param toDegrees the end angle of the 3D rotation //結束角度
     * @param centerX the X center of the 3D rotation //x中軸線
     * @param centerY the Y center of the 3D rotation //y中軸線
     * @param reverse true if the translation should be reversed, false otherwise//是否反轉
     */
    public Rotate3dAnimation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;//Z軸移動的距離,這個來影響視覺效果,能夠解決flip animation那個給人看似放大的效果
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        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 = t.getMatrix();

        Log.i("interpolatedTime", interpolatedTime+"");
        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

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

dialog實現3D翻轉代碼,

說明:動畫部分的代碼是拿的搜的的那篇文章的.net

public class MyDialog extends Dialog {

    @BindView(R.id.et_user_name)
    EditText etUserName;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.cb_auto_login)
    CheckBox cbAutoLogin;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.btn_back)
    Button btnBack;
    @BindView(R.id.container)
    RelativeLayout container;
    private Context context;

    @BindView(R.id.ll_register)
    LinearLayout llRegister;


    //接口回調傳遞參數
    private OnClickListenerInterface mListener;
    private View view;
//
    private String strContent;


    private int centerX;
    private int centerY;
    private int depthZ = 700;//修改此處能夠改變距離來達到你滿意的效果
    private int duration = 300;//動畫時間
    private Rotate3dAnimation openAnimation;
    private Rotate3dAnimation closeAnimation;

    private boolean isOpen = false;

    public interface OnClickListenerInterface {

        /**
         * 確認,
         */
        void doConfirm();

        /**
         * 取消
         */
//        public void doCancel();
    }

    public MyDialog(Context context) {
        super(context);
        this.context = context;
    }

    public MyDialog(Context context, String content) {
        super(context);
        this.context = context;
        this.strContent = content;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉系統的黑色矩形邊框
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        init();
    }

    public void init() {
        LayoutInflater inflater = LayoutInflater.from(context);
        view = inflater.inflate(R.layout.dialog_my, null);
        setContentView(view);
        ButterKnife.bind(this);
        etPassword.setTypeface(Typeface.DEFAULT);
        etPassword.setTransformationMethod(new PasswordTransformationMethod());
        tvForgetPwd.setOnClickListener(new OnWidgetClickListener());
        btnBack.setOnClickListener(new OnWidgetClickListener());
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = context.getResources().getDisplayMetrics(); // 獲取屏幕寬、高用
        lp.width = (int) (d.widthPixels * 0.8); // 寬度設置爲屏幕的0.8
        lp.height = (int) (d.heightPixels * 0.6); // 高度設置爲屏幕的0.6
        dialogWindow.setAttributes(lp);
        setCanceledOnTouchOutside(false);
        setCancelable(true);
    }

    public void setClicklistener(OnClickListenerInterface clickListenerInterface) {
        this.mListener = clickListenerInterface;
    }

    private class OnWidgetClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {

            int id = v.getId();
            switch (id) {
                case R.id.tv_forget_pwd:
                    startAnimation();
                    break;
                case R.id.btn_back:
                    startAnimation();
                    break;
            }
        }
    }

    private void startAnimation() {
        //接口回調傳遞參數
        centerX = container.getWidth() / 2;
        centerY = container.getHeight() / 2;
        if (openAnimation == null) {
            initOpenAnim();
            initCloseAnim();
        }

        //用做判斷當前點擊事件發生時動畫是否正在執行
        if (openAnimation.hasStarted() && !openAnimation.hasEnded()) {
            return;
        }
        if (closeAnimation.hasStarted() && !closeAnimation.hasEnded()) {
            return;
        }

        //判斷動畫執行
        if (isOpen) {

            container.startAnimation(openAnimation);

        } else {

            container.startAnimation(closeAnimation);

        }
        isOpen = !isOpen;
    }

    /**
     *注意旋轉角度
     */
    private void initOpenAnim() {
        //從0到90度,順時針旋轉視圖,此時reverse參數爲true,達到90度時動畫結束時視圖變得不可見,
        openAnimation = new Rotate3dAnimation(0, 90, centerX, centerY, depthZ, true);
        openAnimation.setDuration(duration);
        openAnimation.setFillAfter(true);
        openAnimation.setInterpolator(new AccelerateInterpolator());
        openAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llRegister.setVisibility(View.GONE);
                llContent.setVisibility(View.VISIBLE);
                //從270到360度,順時針旋轉視圖,此時reverse參數爲false,達到360度動畫結束時視圖變得可見
                Rotate3dAnimation rotateAnimation = new Rotate3dAnimation(270, 360, centerX, centerY, depthZ, false);
                rotateAnimation.setDuration(duration);
                rotateAnimation.setFillAfter(true);
                rotateAnimation.setInterpolator(new DecelerateInterpolator());
                container.startAnimation(rotateAnimation);
            }
        });
    }

   
    private void initCloseAnim() {
        closeAnimation = new Rotate3dAnimation(360, 270, centerX, centerY, depthZ, true);
        closeAnimation.setDuration(duration);
        closeAnimation.setFillAfter(true);
        closeAnimation.setInterpolator(new AccelerateInterpolator());
        closeAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llRegister.setVisibility(View.VISIBLE);
                llContent.setVisibility(View.GONE);
                Rotate3dAnimation rotateAnimation = new Rotate3dAnimation(90, 0, centerX, centerY, depthZ, false);
                rotateAnimation.setDuration(duration);
                rotateAnimation.setFillAfter(true);
                rotateAnimation.setInterpolator(new DecelerateInterpolator());
                container.startAnimation(rotateAnimation);
            }
        });
    }
}

Demo下載

相關文章
相關標籤/搜索