移动drawable跟随手指

时间:2012-02-24 08:36:12

标签: android graphics

我有扩展View的课程。

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 个答案:

答案 0 :(得分:5)

这些Youtube教程就是这样做的;

链接: https://buckysroom.org/videos.php?cat=6

只需观看教程717273即可。

答案 1 :(得分: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坐标重新绘制drawable。