如何使用RotateAnimation旋转圆圈?

时间:2010-06-15 13:58:37

标签: android rotation imageview

我希望我的圆形图像(ImageView)在用户触摸时旋转并拖动它。如果用户将其拖动到右侧,则应向右旋转,反之亦然。就像你旋转DJ碟片一样,如果你知道我的意思。我用OnTouchListener和RotateAnimation玩了一下但是我无处可去。

有什么想法吗?

1 个答案:

答案 0 :(得分:8)

假设您要旋转ImageView mCircle。您必须使用RotateAnimation来旋转它。在OnTouch方法中,确定用户手指的角度。

例如,在您的主要活动中执行以下操作

private ImageView mCircle;
private double mCurrAngle = 0;
private double mPrevAngle = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mCircle = (ImageView) findViewById(R.id.circle);
    mCircle.setOnTouchListener(this); // Your activity should implement OnTouchListener
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    final float xc = mCircle.getWidth() / 2;
    final float yc = mCircle.getHeight() / 2;

    final float x = event.getX();
    final float y = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN: {
        mCircle.clearAnimation();
        mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
        break;
    }
    case MotionEvent.ACTION_MOVE: {
        mPrevAngle = mCurrAngle;
        mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
        animate(mPrevAngle, mCurrAngle, 0);
        break;
    }
    case MotionEvent.ACTION_UP : {
        mPrevAngle = mCurrAngle = 0;
        break;
    }
    }

    return true;
}

private void animate(double fromDegrees, double toDegrees, long durationMillis) {
    final RotateAnimation rotate = new RotateAnimation((float) fromDegrees, (float) toDegrees,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    rotate.setDuration(durationMillis);
    rotate.setFillEnabled(true);
    rotate.setFillAfter(true);
    mCircle.startAnimation(rotate);
}