Search code examples
androidgesturerotateanimation

android smooth rotation using SimpleOnGestureListener


I have circle which I want to rotate. I am using SimpleOnGestureListener to handle gestures, especially onScroll method.

        @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {

        float lWidth = e1.getX() - centeralPointX;
        float lHeight = e1.getY() - centeralPointY;
        float lRadius = FloatMath.sqrt(lWidth * lWidth + lHeight * lHeight);

        if ((lRadius <= bigCircleRadius) && (lRadius >= smallCircleRadius)) {

            mLastAngle = (float) (Math.atan(lHeight / lWidth) * 180 / Math.PI)
                    + step / 2;

            float currWidth = e2.getX() - centeralPointX;
            float currHeight = e2.getY() - centeralPointY;
            mCurrentAngle = (float) (Math.atan(currHeight / currWidth) * 180 / Math.PI)
                    + step / 2;

            mAngle = mLastAngle - mCurrentAngle;
            mLastAngle = mCurrentAngle;

            // show angles
            TextView lastANGLE, endANGLE, ANGLE;
            lastANGLE = (TextView) findViewById(R.id.currentAngle);
            lastANGLE.setText("last " + mLastAngle);
            endANGLE = (TextView) findViewById(R.id.endAngle);
            ANGLE = (TextView) findViewById(R.id.angle);

            endANGLE.setText("current " + mCurrentAngle);
            ANGLE.setText("ANGLE " + mAngle);

            rotation = (float) (-mAngle - step / 2);
            if (rotate != null && !rotate.hasEnded()) {
                rotate.cancel();
                rotate.reset();
            }
            rotate = RotateCircle(radius, radius);
            words_layout.startAnimation(rotate);
            return true;
        } else
            return false;
    }

But it doesn't work correctly. I want that circle will rotate smoothly but it doesn't. How can I do this? I have tried to use onFling method but it rotate my circle after end of the movement. But I need rotate it during movement.


Solution

  • You can try to override View.onTouchEvent(MotionEvent e) like this :

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastEventX = e.getX();
                lastEventY = e.getY();
                return true;
    
            case MotionEvent.ACTION_MOVE:
                // put your code to rotate here using lastEventX and lastEventY instead of e1.getX() and e1.getY()
                return true;
        }
        return super.onTouchEvent(MotionEvent event);
    }