Android 遊戲轉盤動畫 轉盤指針動畫

原作者Githubhttps://github.com/thanhniencung/LuckyWheel
自己的Github:https://github.com/YangQiRen/LuckyWheel

因為自己的需求,所以加入了指針(Cursor)的動畫

Cursor Animation

cursor Swinging small animation
        // 200ms 指針從0度跳到-30度之後跳回來0度,因為指針回彈較快,使用加速度,雖然看不太出來
        animCursor = ObjectAnimator.ofFloat(cursorView, "rotation", 0f, -30f, 0f);
        animCursor.setDuration(200);
        animCursor.setInterpolator(new AccelerateInterpolator());
        animCursor.setRepeatCount(0);
        animCursor.setRepeatMode(ValueAnimator.RESTART);
        
        // 設定cursor旋轉的中心點
        cursorView.setPivotX(0f);
        cursorView.setPivotY(cursorView.getWidth()/2);

Wheel view slow down animation

Decelerate Interpolator to slow down the animation
        // 算角度,要轉幾圈(360度 * 圈數 - 目標角度)跟輪盤轉的角度一樣
        float targetAngle = 360f * SECOND_OF_ROUND - getAngleOfIndexTarget(targetIndex) ;

        // slow down
        animCursorSlowDown = ValueAnimator.ofFloat(0, targetAngle);
        // 10秒 1000=1秒
        animCursorSlowDown.setDuration(SECOND_OF_ROUND * 1000);
        animCursorSlowDown.setInterpolator(new DecelerateInterpolator());
        animCursorSlowDown.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(final ValueAnimator animation) {
                // 目前的角度 + 一開始的偏移角度22.5
                float currentAngle = (float) animation.getAnimatedValue() + ((360f / GRID_OF_LUCKY_WHEEL) / 2);

                // 這次轉的角度
                float  angleOfThisTurn = currentAngle - preAngle;
                // 是否執行動畫
                int isStartAnimation = (int) (angleOfThisTurn / (360f / GRID_OF_LUCKY_WHEEL));

                if ( isStartAnimation > 0 && !animCursor.isRunning() ) {
                    Log.e("animCursor", "start()");
                    preAngle += isStartAnimation * (360f / GRID_OF_LUCKY_WHEEL);
                    animCursor.start();
                }
            }
        });
        animCursorSlowDown.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                preAngle = 0;
            }
        });

        if ( !animCursorSlowDown.isStarted() ) {
            animCursorSlowDown.start();
        }

這樣就完成了,就好像指針被輪盤撥動的感覺。
完整代碼在https://github.com/YangQiRen/LuckyWheel

留言

這個網誌中的熱門文章

Android - 使用 adb 安装apk

Android ContentProvider 實現多個應用程式共享資料

Android TextView autosizing 自動調整大小