title: Android Canvas Check if Point is on Line
body: <p>I have a Custom View which draws lines an saves them to an ArrayList. What I want to be able to do is check if a specified point is on a line inside the Arraylist and return the line. I have been able to do this when the line is straight by using <code>if (l.startX == l.stopX &amp;&amp; l.startY &lt; l.stopY</code> but this doesn't work if the line is on an angle. I would also like to do this with drawText and drawCircle. Is there some simple way of doing this that I have missed?</p>
  
  <p>DrawView.java</p>
  
  <pre><code>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&lt;Line&gt; lines = new ArrayList&lt;Line&gt;();
  
    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) &amp;&amp;
          lines.size() &gt; 0) {
        Line current = lines.get(lines.size() - 1);
        current.stopX = event.getX();
        current.stopY = event.getY();
        Invalidate();
        return true;
      }
      else {
        return false;
      }
    }
  }
  </code></pre>