所有案例都涉及Bresenham的线算法

时间:2012-07-26 22:00:28

标签: c# .net algorithm line bresenham

我需要检查一行中的所有像素,所以我使用Bresenham的算法来访问其中的每个像素。特别是我需要检查所有像素是否都位于位图的有效像素上。这是代码:

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用于检查线像素是否在有效位图上。我将创建的像素添加到List<Point>以逐点渲染其元素,并确保Bresenham检查正确的像素(确实如此)。问题是我的算法并没有涵盖所有情况,只有50%左右。

P.S:我的坐标系原点位于左上角(x从左到右增长,y从上到下)

1 个答案:

答案 0 :(得分:31)

查找完整版本:

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 ;
        }
    }
}