我有一個自定義視圖,它繪製線條並將它們保存到ArrayList。我想要做的是檢查一個指定的點是否在Arraylist中的一行上並返回該行。當直線使用if (l.startX == l.stopX && l.startY < l.stopY
時,我可以做到這一點,但如果線條處於某個角度,則此功能無效。我也想用drawText和drawCircle做到這一點。有沒有一些簡單的方法來做到這一點,我錯過了?Android Canvas檢查點是否在線
DrawView.java
class Line {
float startX, startY, stopX, stopY;
public Line(float startX, float startY, float stopX, float stopY) {
this.startX = startX;
this.startY = startY;
this.stopX = stopX;
this.stopY = stopY;
}
public Line(float startX, float startY) { // for convenience
this(startX, startY, startX, startY);
}
}
public class DrawView extends View {
Paint paint = new Paint();
ArrayList<Line> lines = new ArrayList<Line>();
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
for (Line l : lines) {
canvas.drawLine(l.startX, l.startY, l.stopX, l.stopY, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
lines.add(new Line(event.getX(), event.getY()));
return true;
}
else if ((event.getAction() == MotionEvent.ACTION_MOVE ||
event.getAction() == MotionEvent.ACTION_UP) &&
lines.size() > 0) {
Line current = lines.get(lines.size() - 1);
current.stopX = event.getX();
current.stopY = event.getY();
Invalidate();
return true;
}
else {
return false;
}
}
}
如果mX = 0,您的解決方案可能會導致運行時錯誤。我在http://stackoverflow.com/questions/20887806/does-a-line-contain-a-point/23388247#23388247上發佈了一個較短的版本,可以解決這個問題。 –