问题描述
我希望我的圆形图像 (ImageView) 在用户触摸并拖动它时旋转.如果用户向右拖动它,它应该向右旋转,反之亦然.就像您旋转 DJ 光盘一样,如果您知道我的意思的话.我用 OnTouchListener 和 RotateAnimation 玩了一会儿,但我一无所获.
I want my circle image (ImageView) to rotate as the user touch and drag it. If the user drags it to the right, it should spin right and vice versa. Like when you spin a DJ disc, if you know what i mean. I've played around a bit with OnTouchListener and RotateAnimation but i'm getting nowhere.
有什么想法吗?
推荐答案
假设您有想要旋转的 ImageView mCircle
.您必须使用 RotateAnimation
来旋转它.在 OnTouch
方法中确定用户手指的角度.
Let's assume you have ImageView mCircle
which you want to rotate. You have to use RotateAnimation
to rotate it. In OnTouch
method determine the angle where user's finger is.
例如,在您的主要活动中执行以下操作
For example, in your main activity do the following
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);
}
这篇关于如何使用 RotateAnimation 旋转一个圆圈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!