【问题标题】:How can i use RotateAnimation to rotate a circle?如何使用 RotateAnimation 旋转一个圆圈?
【发布时间】:2010-06-15 13:58:37
【问题描述】:

我希望我的圆形图像 (ImageView) 在用户触摸并拖动它时旋转。如果用户向右拖动它,它应该向右旋转,反之亦然。就像您旋转 DJ 光盘一样,如果您知道我的意思的话。我用 OnTouchListener 和 RotateAnimation 玩了一会儿,但我一无所获。

有什么想法吗?

【问题讨论】:

  • 也许你可以展示你的尝试,并详细说明什么不起作用。
  • 事实上我什至不知道如何继续我想要的。我只需要一些想法如何完成。

标签: android rotation imageview


【解决方案1】:

假设您有要旋转的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);
}

【讨论】:

  • 太棒了!简单而优雅。谢谢@vasart!
  • 我已经修改了你的代码,让它像旋钮一样工作,角度在 -120 到 120 之间。但是每当我 ActionDown 它移回它的原始位置时,我想保存最后一次触摸的角度,每当我 ActionDown 它就会在最后一个位置。
  • @Nepster,尝试评论clearAnimation() 电话。
  • @vasart,评论 clearAnimation() 没有帮助。
猜你喜欢
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2021-07-30
  • 2023-03-14
  • 2013-03-31
相关资源
最近更新 更多