我在Canvas上有一些多边形。 我如何倾听点击任何多边形?
我有一个方法
public void drawPolygon(ChartPolygon polygon) {
List<Point> points = polygon.getPoints();
int size = points.size();
if (size < 2) {
return;
}
Paint polyPaint = new Paint();
polyPaint.setColor(polygon.getColor());
polyPaint.setStyle(Style.FILL);
Path polyPath = new Path();
polyPath.moveTo(points.get(0).getX(), points.get(0).getY());
for (Point point : points) {
polyPath.lineTo(point.getX(), point.getY());
}
canvas.drawPath(polyPath, polyPaint);
}
答案 0 :(得分:4)
我会保留一份区域列表。无论何时绘制新的多边形,使用与绘制相同的路径来定义新的区域:
Region r = new Region();
r.setPath(path, clip);
regionList.add(r);
可以定义剪辑,例如由
Region clip = new Region(0, 0, canvas.getWidth(), canvas.getHeight());
最后,当您通过regionList检测onTouchListener循环中的触摸并检查时,触摸点(由x和y给出)是否在区域内:
for (int i = 0; i < regionList.size(); i++) {
Region r = regionList.get(i);
if (r.contains(x,y) {
selectedRegionIndex = i;
break;
}
}
答案 1 :(得分:1)
阅读this post,这篇文章可以帮助您
首先,您可以在屏幕中获得点击事件的X和Y位置。 您可以在Activity extends
中实现onTouchEvent函数@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (topTouchArea.contains(event.getX(), event.getY())) {
currentTouch = TOUCH_TOP;
} else if (RightTouchArea.contains(event.getX(),event.getY())) {
currentTouch = TOUCH_RIGHT;
} else if (LeftTouchArea.contains(event.getX(),event.getY())) {
currentTouch = TOUCH_LEFT;
} else {
return false; //Return false if user touches none of the corners
}
return true;
}
}
现在(总是在你的onTouchEvent中)函数,你可以评估多边形的位置和区域。
case MotionEvent.ACTION_MOVE:
switch (currentTouch) {
case TOUCH_TOP:
top.x = event.getX();
top.y = event.getY();
invalidate();
return true;
case TOUCH_RIGHT:
Right.x = event.getX();
Right.y = event.getY();
invalidate();
return true;
case TOUCH_LEFT:
Left.x = event.getX();
Left.y = event.getY();
invalidate();
return true;
}
case MotionEvent.ACTION_UP:
switch (currentTouch) {
case TOUCH_TOP:
top.x = event.getX();
top.y = event.getY();
invalidate();
currentTouch = NONE;
return true;
case TOUCH_RIGHT:
Right.x = event.getX();
Right.y = event.getY();
invalidate();
currentTouch = NONE;
return true;
case TOUCH_LEFT:
Left.x = event.getX();
Left.y = event.getY();
invalidate();
currentTouch = NONE;
return true;
}
return false;
所有帖子都在article link
中