# Check if a pixel is aligned with others

The mathematical definition of a line is simple: `y = a*x+c` Where a is the slope and c is the value where the line intersects the y axis. In computer graphics this is not so trivial any more: Any line drawn within the image never intersects with the y-axis (the left border). Additionally the values defined by the pixel coordinates are discreet and a line definition may not pass through the heart of the pixel.
Here is a method that checks if a line (defined by a list of points) is aligned with a point. This point is a neighbour of either end of the line.
A point is defined through the following interface:

```public interface Point {
/**
* Retrieve X-coordinate of the point
* @return X-coordinate
*/
public int getX();
/**
* Retrieve Y-coordinate of the point
* @return Y-coordinate
*/
public int getY();
/**
* Check if the Point p is a neighbour of this.
* @param p Point to be checked
* @return true if the point is one of the 8 neighbours
*/
public boolean isNeighbour(Point p);
}
```

To evaluate the new point it must be a neighbour of either end and have this endpoint as sole neighbour. Then the slopes of the line between the endpoints and the slope of the point with the furtherest endpoint are compared with a delta of 0.5. Either slope may be infinite ore not a number (division by 0). If one slope is infinite the other must be steep. Otherwise if one is not a number the other must be shallow.

```/**
* Check if the point is aligned with all other points.
* @param p Point to be checked
* @return true if the point is aligned
*/
public boolean isOnLine(Point p){
Point p1 = getFirstPoint();
if (points.size()==1 && p1.isNeighbour(p)){
return true;
}
for (Point lp : points){
if (lp.isNeighbour(p) && !lp.equals(getFirstPoint()) && !lp.equals(getLastPoint())){
return false;
}
}
Point p2 = getLastPoint();
if (p1.isNeighbour(p)){
// Swap p1 and p2
Point temp = p2;
p2=p1;
p1=temp;
}
double dy1 = ((double)p.getY()-p1.getY());
double dx1 = ((double)p.getX()-p1.getX());
double slope1 = dy1/dx1;
double dy2 = ((double)p2.getY()-p1.getY());
double dx2 = ((double)p2.getX()-p1.getX());
double slope2 = dy2/dx2;
if (slope1==slope2) return true;
if (Double.isInfinite(slope1)){
// slope2 must be very steep
if (slope2>=points.size()*0.9) return true;
return false;
}
if (Double.isInfinite(slope2)){
// slope1 must be very steep
if (slope1>=points.size()*0.9) return true;
return false;
}
if (Double.isNaN(slope1)){
// slope2 must be very shallow
if (slope2< =1/(double)points.size()) return true;
return false;
}
if (Double.isNaN(slope1)){
// slope1 must be very shallow
if (slope1<=1/(double)points.size()) return true;
return false;
}
return slope1<=slope2+0.5 || slope1>=slope2-0.5;
}
```