我有扩展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
写下什么来做我想做的事?
答案 0 :(得分:5)
答案 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。