我希望我的圆形图像(ImageView)在用户触摸并拖动它时旋转。如果用户向右拖动它,它应该向右旋转,反之亦然。就像您旋转 DJ 光盘一样,如果您知道我的意思的话。我用 OnTouchListener 和 RotateAnimation 玩了一会儿,但我无处可去。
有任何想法吗?
让我们假设你有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);
}