2011-10-12 43 views
0

我有一個imageview其中包含一個箭頭圖片。當用戶在imageview上觸摸他的手指,然後根據從初始位置imageview的運動,我計算角度(角位移)。角度計算多次調用imageview觸摸事件

最初我在模擬器上測試這個代碼,所以當我在imageview上單擊鼠標並旋轉imageview並刪除鼠標時,我發現角度計算函數被稱爲多次。但這不是我想要的。

我希望它只被調用一次,這取決於用戶何時旋轉imageview並離開他的手指。

這是我的代碼: - 請注意mTop是我在下面的代碼中的imageview。

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.decodeResource(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); 
} 

=========================================== =========

我對Ontouch事件修改後的代碼: -

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; 
    } 
+0

什麼是MTOP在上面的代碼 – Nepster

回答

2

我不完全相信你試圖基於whaty OU完成這裏的東西。但是我可以告訴你,你的onTouch()會通過MotionEvent.ACTION_MOVE得到很多回調。基本上,當你的手指觸摸屏幕時,這個方法將會被系統調用的速度一遍又一遍地調用。

您可能需要在MotionEvent.ACTION_UP的情況下做旋轉,只有在手指離開屏幕時纔會調用該旋轉。

編輯:

在代碼中你還有這個if語句嗎?

if (motion.getAction() != MotionEvent.ACTION_DOWN && 
     motion.getAction() != MotionEvent.ACTION_MOVE) { 
    return false; 
} 

如果因此你可能需要將其刪除

+0

謝謝!這回答了我的問題!!!現在讓我試試:) – Ruchira

+0

當我將角度旋轉代碼移動到ACTION_UP時,imageview停止響應觸摸事件。 – Ruchira

+0

發佈您的代碼,因爲它現在 – FoamyGuy