我想通过使用用户运动事件来旋转图像视图,然后图像必须以减速的角速度继续旋转。我能够使用 ontouchlistener 旋转图像视图。然后我尝试计算视图的速度并将其添加到视图动画中,但不幸的是应用程序在后期崩溃了。此代码中的速度部分不完整,但我不明白如何实现这部分。请帮忙!!!这是我的代码
public class MainActivity extends Activity implements OnTouchListener {
private static Bitmap imageOriginal;
private static Matrix matrix;
private ImageView bottle;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (imageOriginal == null) {
imageOriginal = BitmapFactory.decodeResource(getResources(),
R.drawable.bottle);
}
if (matrix == null) {
matrix = new Matrix();
} else {
matrix.reset();
}
bottle = (ImageView) findViewById(R.id.bottle_image);
bottle.setOnTouchListener(this);
}
private double startAngle, currentAngle;
private VelocityTracker vTracker = null;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
if (vTracker == null) {
vTracker = VelocityTracker.obtain();
} else {
vTracker.clear();
}
vTracker.addMovement(event);
startAngle = getAngle(event.getY(), event.getX());
break;
case MotionEvent.ACTION_MOVE:
vTracker.addMovement(event);
vTracker.computeCurrentVelocity(1000);
currentAngle = getAngle(event.getY(), event.getX());
rotateBottle(startAngle, currentAngle);
startAngle = currentAngle;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
private double getAngle(double x1, double y1) {
double x = x1 - (bottle.getWidth() / 2);
double y = bottle.getHeight() - y1 - (bottle.getHeight() / 2);
switch (getQuadrant(x, y)) {
case 1:
return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
case 2:
return 180 - Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
case 3:
return 180 + (-1 * Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
case 4:
return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
default:
return 0;
}
}
private int getQuadrant(double x, double y) {
if (x >= 0)
return y >= 0 ? 1 : 4;
else
return y >= 0 ? 2 : 3;
}
private void rotateBottle(double start, double end) {
final RotateAnimation rotate = new RotateAnimation((float) start,
(float) end, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(0);
rotate.setFillEnabled(true);
rotate.setFillAfter(true);
bottle.startAnimation(rotate);
}
}