我有画布和要在触摸事件上拖动的3个点。这是我的代码。
public class Canvas7 extends View {
Paint p;
PointF point1;
PointF point2;
PointF point3;
PointF currentPoint = null;
public Canvas7(Context context) {
super(context);
p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setStrokeWidth(3);
point1 = new PointF(150, 200);
point2 = new PointF(150, 500);
point3 = new PointF(250, 300);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawARGB(80, 102, 204, 255);
p.setStyle(Paint.Style.FILL);
p.setColor(Color.GREEN);
canvas.drawCircle(point1.x, point1.y, 10, p);
p.setStyle(Paint.Style.FILL);
p.setColor(Color.BLUE);
canvas.drawCircle(point2.x, point2.y, 10, p);
canvas.drawCircle(point3.x, point3.y, 10, p);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
if (x > 0 && y > 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
currentPoint = getPoint(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if(currentPoint != null) {
currentPoint.set(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
currentPoint = null;
invalidate();
break;
}
}
return true;
}
private PointF getPoint(float x, float y) {
if ((x < (point1.x + 20) && x > (point1.x - 20)) && (y < (point1.y + 20)) && y > (point1.y - 20)) {
point1.set(x, y);
return point1;
} else if ((x < (point2.x + 20) && x > (point2.x - 20)) && (y < (point2.y + 20)) && y > (point2.y - 20)) {
point2.set(x, y);
return point2;
} else if ((x < (point3.x + 20) && x > (point3.x - 20)) && (y < (point3.y + 20)) && y > (point3.y - 20)) {
point3.set(x, y);
return point3;
}
return null;
}
}
-更新-当前代码可以正常工作。
代码不起作用。当我单击要移动的点时,它不会移动。当我移除if((point.x) == x || (point.y) == y)
支票时,我可以移动该点,但是当我移除支票时,所有点都一起移动。所以我只想拖动一点。
例如,如果我触摸point1
,则只想移动point1
,仅移动。当我单击point2
时,我只想移动point2。我想你明白了。
我该怎么做?谢谢。
================================================ ==========================
答案 0 :(得分:2)
如果您的手指尺寸为1像素,并且可以触摸放置点的确切位置,则您的代码基本上可以正常工作。 :)
因此,您必须在点周围引入一个逻辑区域并进行处理。例如,圆是点的良好表示。如果您触摸屏幕并获得x
,y
坐标,则只需检查哪个点是最接近的点,然后检查距离即可。
步骤:
如果event.getAction() == MotionEvent.ACTION_DOWN
为真:
Elseif event.getAction() == MotionEvent.ACTION_MOVE
是正确的:
Elseif event.getAction() == MotionEvent.ACTION_UP
是正确的: