Непрерывно вращать изображение OnTouchEvent в Android - PullRequest
0 голосов
/ 02 ноября 2011

Я новичок в разработке для Android и пытаюсь понять, как непрерывно поворачивать изображение с помощью onTouchEvent. Я использую следующий код для поворота изображения на 10 градусов, когда onTouchEvent обнаруживает касание экрана и наоборот, но я хочу, чтобы изображение продолжало вращаться с интервалами в 10 градусов, пока происходит событие onTouchEvent. Спасибо!

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_DOWN) {
            degrees=degrees+10;
            make(degrees);
            }
        else if(event.getAction()==MotionEvent.ACTION_UP) {
            degrees=degrees-10;
            make(degrees);
            }
        return super.onTouchEvent(event);
        }
}

Ответы [ 3 ]

0 голосов
/ 02 ноября 2011

Насколько я понимаю, вы хотите начать вращение изображения, когда пользователь кладет палец на экран, и прекратить вращение, когда пользователь убирает палец с экрана.

Если этоправильно, вам нужно запустить поток или обработчик на фоне, который будет сохранять.

Может быть что-то вроде:

// flag to tell if the rotation should continue
private boolean keepRotating = false;
// instance variable to keep the current rotation degrees
private int degrees = 0;
// rotation interval in milliseconds
private static final int INTERVAL = 100;

@Override
public boolean onTouchEvent(MotionEvent event)
{
    switch (event.getAction())
    {
        case MotionEvent.ACTION_DOWN:
            startRotating();
            break;
        case MotionEvent.ACTION_UP:
            stopRotating();
            break;
    }

    return super.onTouchEvent(event);
}

public void startRotating()
{
    if (!keepRotating)
    {
        keepRotating = true;

        final Handler handler = new Handler();

        handler.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                if (keepRotating)
                {
                    degrees = (degrees + 10) % 360;
                    make(degrees);

                    handler.postDelayed(this, INTERVAL);
                }
            }
        }, INTERVAL);
    }
}

public void stopRotating()
{
    keepRotating = false;
}

public void make(int degrees)
{
    Log.i(this.getClass().toString(), "Rotation : " + degrees);

    // Your rotation logic here based on the degrees parameter
    // ...
}
0 голосов
/ 31 декабря 2012

Используйте код ниже

public void startMoving() {
    rotateAnimation1 = null;
    try {
        if (duration < 1500) {
            rotateAnimation1 = new RotateAnimation(0, 360,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation1.setInterpolator(new LinearInterpolator());
            rotateAnimation1.setDuration(duration);
            rotateAnimation1.setRepeatCount(0);
            imgBottle.startAnimation(rotateAnimation1);

            flagSpinAvailable = false;

            rotateAnimation1.setAnimationListener(new AnimationListener() {
                public void onAnimationStart(Animation anim) {
                };

                public void onAnimationRepeat(Animation anim) {
                };

                public void onAnimationEnd(Animation anim) {
                    duration = duration + 70;
                    startMoving();
                };
            });

        } else {
            duration = duration + 100;
            final float degree = (float) (Math.random() * 360);
            degreeBack = 360 - degree;
            rotateAnimation2 = new RotateAnimation(0, degree,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation2.setInterpolator(new LinearInterpolator());
            rotateAnimation2.setDuration(duration);
            rotateAnimation2.setRepeatCount(0);
            rotateAnimation2.setFillAfter(true);
            imgBottle.startAnimation(rotateAnimation2);

            rotateAnimation2.setAnimationListener(new AnimationListener() {
                public void onAnimationStart(Animation anim) {
                };

                public void onAnimationRepeat(Animation anim) {
                };

                public void onAnimationEnd(Animation anim) {
                    afterSpinEnd();
                };
            });

        }
    } catch (Exception e) {
        flagSpinAvailable = true;
        e.printStackTrace();
    }
}

Это мой код для поворота изображения вокруг себя и медленного уменьшения скорости

0 голосов
/ 02 ноября 2011

Использование:

degrees = (degrees + 10) % 360;

// ...

if(degrees < 10) degrees += 360;
degrees = (degrees - 10) % 360;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...