2017-02-23 57 views
0

我試圖創建下面的代碼來檢測兩個手指,並讓它跟蹤不同彩色圓圈表示的運動。但是,我不確定如何有多個圓圈工作。你如何檢測兩個手指繪製兩個獨立的圓?

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.support.v4.view.MotionEventCompat; 
import android.util.AttributeSet; 
import android.view.MotionEvent; 
import android.view.View; 

public class MyExtendedView extends View { 

    static int touchDoneCounter = 2; 

    static String DEBUG_TAG = "CUSTOM_VIEW_INFO"; 

    float x=0, y=0; 

    // The constructor is called first 
    public MyExtendedView(Context ctx, AttributeSet attrs) { 

     super(ctx, attrs); 

     // Set the background color to black 
     this.setBackgroundColor(Color.BLACK); 
    } 

    // This method is called before the view is drawn first, on screen rotation and when forceredraw is called 
    protected void onDraw(Canvas canvas) { 

     super.onDraw(canvas); 

     Paint p = new Paint(); 
     p.setColor(Color.YELLOW); 

     Paint g = new Paint(); 
     g.setColor(Color.GREEN); 


     // draw the circle where the touch occurs. At start, x and y are zero so the circle is drawn on top right 
     canvas.drawCircle(x, y, 75f, p); 



    } 



    // This is called when a touch is registered 
    @Override 
    public boolean onTouchEvent(MotionEvent event) { 


     int action = MotionEventCompat.getActionMasked(event); 

     // logging the kind of event we got 
     switch (action) { 
      case MotionEvent.ACTION_DOWN: 
      case MotionEvent.ACTION_POINTER_DOWN: { 
       break; 
      } 

      case MotionEvent.ACTION_MOVE: { // a pointer was moved 
       break; 
      } 

      case MotionEvent.ACTION_UP: 
      case MotionEvent.ACTION_POINTER_UP: 
      case MotionEvent.ACTION_CANCEL: { 
       break; 
      } 
     } 
     //1.5 at this point we re-draw the circle where the touch occurred 
     redrawViewWithCircle(event); 

     return true; 
    } 


    public void redrawViewWithCircle(MotionEvent event) { 

     // Get index 
     int index = MotionEventCompat.getActionIndex(event); 

     // Get coordinates for circle center. Set the instance variables. 
     this.x = (int)MotionEventCompat.getX(event, index); 
     this.y = (int)MotionEventCompat.getY(event, index); 

     // Force the view to redraw. 
     this.postInvalidate(); 

    } 

} 

我想我需要有一個指數和ID,但我不能確定這裏應該放置的位置。我在正確的軌道上嗎?

回答

1

你在正確的軌道上。觸摸的每個手指都會有一個單獨的ID和索引。索引爲0 ... n(其中n是現在向下的手指數),ID可以更高並且有間隙(如果手指擡起)。對於你的應用,通過event.getX(index)和event.getY(index)跟蹤所有的x和y位置並將它們添加到Points列表中。然後,當您繪製時,在列表中的每個點繪製一個圓圈。爲了簡單起見,您可以簡單地清除並重建每個觸摸的列表,因爲我不能100%確定最終會產生什麼效果。

+0

感謝您的提示。目前,我試圖在每次使用兩個手指(而不是一個)時識別應用程序,並使用不同顏色的單獨圓​​圈跟蹤兩個手指移動(一個手指的黃色圓圈和一個綠色的手指其他)。我沒有跟蹤這個x和this.y的x和y位置嗎? – trungnt

+0

你是第一個索引。但是,如果你有多個手指向下,你有多個x和y –

+0

另外哪個手指是第一個索引的變化 –