angle calculation called multiple times for imageview on touch event
I have an imageview which contains an arrow picture.When the user touches his finger on the imageview then depending on the movement of the imageview from initial position, I am calculating the angle(angular displacement).
Initially I am testing this code on emulator, so when I click the mouse on the imageview and rotate imageview and remove mouse, I find that the function for angle calculation is called multiple times.But this is not what I want.
I want it to be called exactly once depending on when the user rotates the imageview and leaves his finger.
Here is my code:- Please note mTop is my imageview in the below code.
public boolean onTouch(View v, MotionEvent motion) {
// TODO Auto-generated method stub
if (motion.getAction() != MotionEvent.ACTION_DOWN &&
motion.getAction() != MotionEvent.ACTION_MOVE) {
return false;
}
// int angle = 0;
switch(motion.getAction())
{
case MotionEvent.ACTION_MOVE:
float dy = -( motion.getY()-mTop.getPivotY());
float dx = -(motion.getX()-mTop.getPivotX());
double r = Math.atan2(dy, dx);
int angle = (int)Math.toDegrees(r);
updateRotation(angle);
break;
}
return true;
}
public void updateRotation(double angle)
{
Bitmap bitmap = BitmapFactory.decodeResou开发者_运维问答rce(getResources(), R.drawable.arrow);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
String filePath = null;
Matrix mtx = new Matrix();
// Log.w(this.getClass().getName(),"The ANGLE IS %f",angle);
// Log.d("ANGLE IS ", Double.toString(angle));
Log.d(this.getClass().getName(), "Value: " + Double.toString(angle));
if(angle > 90)
angle = 90;
mtx.postRotate((float) angle);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
Drawable draw =new BitmapDrawable(bitmap);
mTop.setBackgroundDrawable(draw);
}
====================================================
MY modified code on Ontouch event:-
switch(motion.getActionMasked())
{
case MotionEvent.ACTION_MOVE:
Log.w(this.getClass().getName(),"In MOTION MOVE");
dy = -( motion.getY()-mTop.getPivotY());
dx = -(motion.getX()-mTop.getPivotX());
r = Math.atan2(dy, dx);
break;
case MotionEvent.ACTION_UP:
angle = (int)Math.toDegrees(r);
updateRotation(angle);
break;
default:
break;
}
I am not exactly sure what you are trying to accomplish based on whaty ou have here. But I can tell you your onTouch() is going to get many many call backs with MotionEvent.ACTION_MOVE. Basically the entire time your finger is touching the screen this method is going to be getting called over and over as fast as the system can call it.
You are probably giong to have to do your rotation in the case for MotionEvent.ACTION_UP that only gets called once when the finger lifts off of the screen.
Edit:
Do you still have this if statement in your code?
if (motion.getAction() != MotionEvent.ACTION_DOWN &&
motion.getAction() != MotionEvent.ACTION_MOVE) {
return false;
}
if so you probably need to remove it
精彩评论