2014-09-05 161 views
0

我有一個代碼,用戶可以在屏幕上移動一個透明的矩形。移動畫布矩形觸摸問題(矩形中心)

我面臨的問題是,矩形當我拖動從左上角移動作爲支點,而我希望它從中心樞軸

移動實施例

enter image description here

@Override 
    public boolean onTouchEvent(MotionEvent ev) { 

     switch (ev.getAction()) { 

     case MotionEvent.ACTION_DOWN: { 

      X = (int) ev.getX(); 
      Y = (int) ev.getY(); 
      invalidate(); 

      break; 
     } 

     case MotionEvent.ACTION_MOVE: { 

      X = (int) ev.getX(); 
      Y = (int) ev.getY(); 
      invalidate(); 
      break; 

     } 

     case MotionEvent.ACTION_UP: 

      break; 

     } 
     return true; 
    } 

    @Override 
    public void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     canvas.drawColor(Color.TRANSPARENT); 
     // draw background 
     canvas.drawBitmap(bgr, 0, 0, null); 
     // copy the default overlay into temporary overlay and punch a hole 
     // in it 
     c2.drawBitmap(overlayDefault, 0, 0, null); // exclude this line to 
                // show all as you draw 

     c2.drawRoundRect(new RectF(X, Y, X+350, Y+350), (float)20.0, (float)20.0, pTouch); 
     // draw the overlay over the background 
     canvas.drawBitmap(overlay, 0, 0, null); 
    } 
+2

因此,從X/Y中減去矩形寬度/高度的一半。 – 2014-09-05 02:33:18

回答

0

@Override public boolean onTouchEvent(MotionEvent ev){

switch (ev.getAction()) { 

    case MotionEvent.ACTION_DOWN: { 

     X = (int) ev.getX(); 
     Y = (int) ev.getY(); 
     invalidate(); 

     break; 
    } 

    case MotionEvent.ACTION_MOVE: { 

     X = (int) ev.getX(); 
     Y = (int) ev.getY(); 
     invalidate(); 
     break; 

    } 

    case MotionEvent.ACTION_UP: 

     break; 

    } 
    return true; 
} 

@Override 
public void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    canvas.drawColor(Color.TRANSPARENT); 
    // draw background 
    canvas.drawBitmap(bgr, 0, 0, null); 
    // copy the default overlay into temporary overlay and punch a hole 
    // in it 
    c2.drawBitmap(overlayDefault, 0, 0, null); // exclude this line to 
               // show all as you draw 

    c2.drawRoundRect(new RectF(X-175, Y-175, X+175, Y+175), (float)20.0, (float)20.0, pTouch); 
    // draw the overlay over the background 
    canvas.drawBitmap(overlay, 0, 0, null); 
} 

雖然我會做的是創建具有正確,而且中點值,這樣我就可以實現,如果我觸摸矩形,然後如果是我能夠繼續前進,這將檢查對象的方法。你的代碼所做的是將矩形移動到你觸摸的屏幕的任何位置。