All cases covered Bresenham's line-algorithm

Frank Lioty picture Frank Lioty · Jul 27, 2012 · Viewed 19.6k times · Source

I need to check all pixels in a line, so I'm using Bresenham's algorithm to access each pixel in it. In particular I need to check if all pixels are located on valid pixel of a bitmap. This is the code:

private void Bresenham(Point p1, Point p2, ref List<Point> track) {
  int dx = p2.X - p1.X;
  int dy = p2.Y - p1.Y;

  int swaps = 0;
  if (dy > dx) {
    Swap(ref dx, ref dy);
    swaps = 1;
  }

  int a = Math.Abs(dy);
  int b = -Math.Abs(dx);

  double d = 2*a + b;
  int x = p1.X;
  int y = p1.Y;
  color_track = Color.Blue;
  Check_Pixel(ref area, new Point(x,y));
  track.Clear();
  track.Add(new Point(x, y));

  int s = 1;
  int q = 1;
  if (p1.X > p2.X) q = -1;
  if (p1.Y > p2.Y) s = -1;

  for(int k = 0; k < dx; k++) {
    if (d >= 0) {
      d = 2*(a+b) + d;
      y = y + s;
      x = x + q;
    }
    else {
      if (swaps == 1) y = y + s;
      else x = x + q;
      d = 2 * a + d;
    }
    Check_Pixel(ref area, new Point(x, y));
    track.Add(new Point(x, y));
  }
}

private void Swap(ref int x, ref int y) {
  int temp = x;
  x = y;
  y = temp;
}

Check_Pixel is used to check if the line pixel is on a valid bitmap one. I add the pixel founded to a List<Point> to render point by point his element and be sure Bresenham checks the correct pixels (it does). The problem is that my algorithm doesn't cover all the cases but about 50% of them.

P.S: my coordinates system origin is on the left-upper corner (x grows left to right, y up to down)

Answer

Frank Lioty picture Frank Lioty · Jul 27, 2012

Find the complete version:

public void line(int x,int y,int x2, int y2, int color) {
    int w = x2 - x ;
    int h = y2 - y ;
    int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
    if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
    if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
    if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
    int longest = Math.Abs(w) ;
    int shortest = Math.Abs(h) ;
    if (!(longest>shortest)) {
        longest = Math.Abs(h) ;
        shortest = Math.Abs(w) ;
        if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
        dx2 = 0 ;            
    }
    int numerator = longest >> 1 ;
    for (int i=0;i<=longest;i++) {
        putpixel(x,y,color) ;
        numerator += shortest ;
        if (!(numerator<longest)) {
            numerator -= longest ;
            x += dx1 ;
            y += dy1 ;
        } else {
            x += dx2 ;
            y += dy2 ;
        }
    }
}