首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用RotateAnimation旋转圆?

如何使用RotateAnimation旋转圆?
EN

Stack Overflow用户
提问于 2010-06-15 21:58:37
回答 1查看 6.8K关注 0票数 1

我想让我的圆形图像(ImageView)随着用户的触摸和拖动而旋转。如果用户将它拖到右边,它应该向右旋转,反之亦然。就像你旋转一张DJ碟片,如果你明白我的意思。我尝试过OnTouchListener和RotateAnimation,但一无所获。

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2013-01-13 03:29:10

让我们假设你有想要旋转的ImageView mCircle。你必须使用RotateAnimation来旋转它。在OnTouch方法中,确定用户手指所在的角度。

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

代码语言:javascript
复制
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);
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3045832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档