2012-02-24 59 views
1

我有擴展視圖的類。移動繪圖按照手指

private class Draw2D extends View{ 
      public Draw2D(Context context) { 
     super(context); 
       } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     x = event.getX(); 
     y = event.getY(); 
     switch(event.getAction()){ 
     case MotionEvent.ACTION_MOVE:{ 

      break; 
     } 

     } 
     return super.onTouchEvent(event); 
    } 


    @Override 
    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     Paint paint = new Paint(); 
     paint.setStyle(Paint.Style.FILL); 
     paint.setColor(Color.WHITE); 
     ShapeDrawable rectangle = 
     new ShapeDrawable(new RectShape()); 
     rectangle.getPaint().setColor(Color.GRAY); 
     rectangle.getPaint().setStyle(Paint.Style.STROKE); 
     rectangle.getPaint().setStrokeWidth(3); 
     rectangle.setBounds(50, 30, 200, 150); 
     rectangle.draw(canvas); 
    } 
} 

我想移動我的形狀按照屏幕上的手指。 我應該寫什麼MotionEvent.ACTION_MOVE做我想做的事?

回答

2

您需要跟蹤繪圖的座標,以便您可以與觸摸x,y座標進行比較。

所以基本上:

// can modify to adjust speed at which drawable moves 
int movementSpeed = 2; 

if (drawableX < x) 
    drawableX += movementSpeed; 
else if (drawableX > x) 
    drawableX -= movementSpeed; 

if (drawableY < y) 
    drawableY += movementSpeed; 
else if (drawableY > y) 
    drawableY -= movementSpeed; 

這時需要用更新drawableX重繪的繪製,drawableY座標。