【问题标题】:What is the problem with my midpoint algorithm?我的中点算法有什么问题?
【发布时间】:2021-05-30 17:45:46
【问题描述】:

我刚开始学习处理,但有一些我无法解决的问题。我希望有人能帮助我。这应该画出我可以用mousePressed() 选择起点和终点的线,但在尝试实现之前我失败了。

//int x1, x2, y1, y2;

void setup() {
  size(640, 480);
}
void draw() {
  midpoint(0, 0, 100, 100);
}

//void mousePressed() {
//  pmouseX =x1;
//  pmouseY =y1;
//  mouseX =x2;
//  mouseY =y2;
//}

void midpoint(int x1, int y1, int x2, int y2) {
  int dx, dy, d, x, y;
  dx = x2-x1;
  dy = y2-y1;
  d = 2*dy-dx;
  x = x1;
  y = y1;
  for (int i = 1; i <dx; i++) {
    point(x, y);
    if (d>0) {
      y++;
      d+=2*(dy-dx);
    } else {
      d+=2*dy;
    }
    x++;
  }
}

我的问题是它不会总是画线。 例如

midpoint(0,0,100,100);

它会画出来

midpoint(100,100,0,0);

它什么也没画。

如果我交换点坐标,它应该画同一条线,如果坐标相同,它应该画一个点。

【问题讨论】:

    标签: processing


    【解决方案1】:

    在 Bresenham 的中点线算法中,您必须小心绘制线的梯度,您描述的基本算法仅适用于 0 和 1 之间的梯度。为了处理更陡峭的梯度(m &gt; 1 或 @ 987654322@),你必须切换xy值的角色,因此你必须进入y然后计算x。同样要处理负面步骤只需切换点顺序即可。

    void midpoint(int x1, int y1, int x2, int y2) {
      // Is gradient of line greater than 1
      boolean steep = abs(y2-y1) > abs(x2-x1);
      int temp;
    
      if (steep) {   // If gradient > 1
        // Swap roles of x and y components to step in y instead
        temp = y1;
        y1 = x1;
        x1 = temp;
    
        temp = y2;
        y2 = x2;
        x2 = temp;
      }
    
      if (x2 < x1) {  
        // Swap points such that step in x is positive
        temp = x1;
        x1 = x2;
        x2 = temp;
    
        temp = y1;
        y1 = y2;
        y2 = temp;
      }
    
      // Change in x and y which are now both positive
      int dx = x2 - x1;
      int dy = abs(y2 - y1);
    
      // Step in y
      int sy = y2 > y1 ? 1 : -1;
      int y = y1;
    
      // Decision variable
      int d = 2*dy-dx;
    
      // Small step in x
      for (int x=x1; x<=x2; x++) {
        // Depending on gradient plot x and y
        if (steep) {
          point(y, x);
        } else {
          point(x, y);
        }
    
        // Update decision parameter
        if (d>0) {
          y += sy;
          d+=2*(dy-dx);
        }else{
          d+=2*dy;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2013-12-25
      • 1970-01-01
      • 2011-12-03
      • 2016-09-19
      • 1970-01-01
      • 2011-08-22
      相关资源
      最近更新 更多