我正在开发一个在 map 上绘制节点的应用程序,每个节点都有边,边由它们之间的线表示。我已经使用 Canvas 和 drawLine() 绘制了边缘,但如果线条本身可以点击,这将很有用。我的意思是一种允许用户触摸线或认为他们正在触摸线并且可以触发事件的方法。 (比如显示边缘信息等...)
我无法将触摸事件正确地附加到我用 Canvas 绘制的线条上,因此我考虑将 ImageView 放置在绘制的每条边缘线的两端之间。 ImageView 可以是一个点,因此触摸事件触发的位置很清楚。
有没有人有任何其他建议?我主要是在寻找我错过的想法。也许 Android API 中有一些我不知道的东西可以帮助解决这个问题。
提前感谢您的任何提示!
最佳答案
使用路径画线:
Path linePath;
Paint p;
RectF rectF;
float point1X, point1Y, point2X, point2Y;
// initialize components
// draw the line
linePath.moveTo(point1X, point1Y);
linePath.lineTo(point2X, point2Y);
canvas.drawPath(linePath, p);
linePath.computeBounds(rectF, true);
覆盖 onTouchEvent(MotionEvent)
:
@Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (rectF.contains(touchX, touchY)) {
// line has been clicked
}
break;
}
return true;
}
关于android - 使 Canvas drawLine() 可点击的技术?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18275032/