以下是完成方法。假设您有点,将它们设置为全局变量:
PointF topLeft = new PointF(10,10);
PointF topRight = new PointF(90,10);
PointF bottomLeft = new PointF(10,90);
PointF bottomRight = new PointF(90,90);
您需要做的是在每个点周围创建一个RectF。RectF越大,点的触摸区域就越大。
float sizeOfRect = 5f;
RectF topLeftTouchArea = new RectF(topLeft.x - sizeOfRect, topLeft.y - sizeOfRect, topLeft.x + sizeOfRect, topLeft.y + sizeOfRect);
//Do this for the other points too
定义一些全局变量来跟踪用户在onTouch中的操作。一个int是被触摸的角落,另外四个是角落的标识符。
private final int NONE = -1, TOUCH_TOP_LEFT = 0, TOUCH_TOP_RIGHT = 1, TOUCH_BOT_LEFT = 2, TOUCH_BOT_RIGHT = 3
int currentTouch = NONE
现在,在您的onTouch事件中,您可以像这样检查用户正在触摸的点:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (topLeftTouchArea.contains(event.getX(), event.getY()) {
currentTouch = TOUCH_TOP_LEFT;
} else if (topRightTouchArea.contains(event.getX(),event.getY()) {
currentTouch = TOUCH_TOP_RIGHT;
} else if (botLeftTouchArea.contains(event.getX(),event.getY()) {
currentTouch = TOUCH_BOT_LEFT;
} else if (botRightTouchArea.contains(event.getX(), event.getY()) {
currentTouch = TOUCH_BOT_RIGHT;
} else {
return false;
}
return true;
case MotionEvent.ACTION_MOVE:
switch (currentTouch) {
case TOUCH_TOP_LEFT:
topLeft.x = event.getX();
topLeft.y = event.getY();
bottomLeft.x = topLeft.x;
topRight.y = topLeft.y;
invalidate();
return true;
case TOUCH_TOP_RIGHT:
topRight.x = event.getX();
topRight.y = event.getY();
topLeft.y = topRight.y;
bottomRight.x = topRight.x;
invalidate();
return true;
case TOUCH_BOT_LEFT:
bottomLeft.x = event.getX();
bottomLeft.y = event.getY();
bottomRight.y = bottomLeft.y;
topLeft.x = bottomLeft.x;
invalidate();
return true;
case TOUCH_BOT_RIGHT:
bottomRight.x = event.getX();
bottomRight.y = event.getY();
topRight.x = bottomRight.x;
bottomLeft.y = bottomRight.y;
invalidate();
return true;
}
return false;
case MotionEvent.ACTION_UP:
switch (currentTouch) {
case TOUCH_TOP_LEFT:
topLeft.x = event.getX();
topLeft.y = event.getY();
bottomLeft.x = topLeft.x;
topRight.y = topLeft.y;
invalidate();
currentTouch = NONE;
return true;
case TOUCH_TOP_RIGHT:
topRight.x = event.getX();
topRight.y = event.getY();
topLeft.y = topRight.y;
bottomRight.x = topRight.x;
invalidate();
currentTouch = NONE;
return true;
case TOUCH_BOT_LEFT:
bottomLeft.x = event.getX();
bottomLeft.y = event.getY();
bottomRight.y = bottomLeft.y;
topLeft.x = bottomLeft.x;
invalidate();
currentTouch = NONE;
return true;
case TOUCH_BOT_RIGHT:
bottomRight.x = event.getX();
bottomRight.y = event.getY();
topRight.x = bottomRight.x;
bottomLeft.y = bottomRight.y;
invalidate();
currentTouch = NONE;
return true;
}
return false;
}
}
这段代码会在你的点周围画一个矩形。可以想象在图片中的点周围画出方框,这些方框是通过Rect对象创建的“触摸区域”。矩形的大小由sizeOfRect设定。在onTouchEvent事件中,会检查每个矩形对象,看用户的触摸是否在矩形内部,从而判断用户是否试图触摸该点。