【问题标题】:All cases covered Bresenham's line-algorithm [closed]所有案例都涵盖了 Bresenham 的线算法 [关闭]
【发布时间】:2012-07-26 22:00:28
【问题描述】:

我需要检查一行中的所有像素,因此我使用 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&lt;Point&gt; 以逐点渲染他的元素,并确保Bresenham 检查正确的像素(确实如此)。问题是我的算法并没有涵盖所有情况,而是涵盖了大约 50% 的情况。

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

【问题讨论】:

  • pro重新打开:问题写得很好,包括足够数量的代码来重现问题。问题文本包含可以回答的问题陈述。现有的答案很有用。我想添加另一个(更新的)答案,但不能。

标签: c# .net algorithm line bresenham


【解决方案1】:

找到完整版本:

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

【讨论】:

  • 最后,Bresenham 的 C# 版本,它实际上涵盖了所有八位字节,并且在一半时间内不会反转点!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
相关资源
最近更新 更多