2013-09-29 81 views
0

我測試了一條線如何可以是1.垂直2.水平3.所有的情況下有正或小於1斜率。該功能的作品,但我想審查它,如果有溢出,丟失測試案例..等等。我剛剛在維基百科上閱讀了該算法,並試圖從維基百科文章中實現它。DDA線算法的實現

// Draw line using DDA Algorithm 
void Graphics::DrawLine(int x1, int y1, int x2, int y2, Color&color) 
{ 

    float xdiff = x1-x2; 
    float ydiff = y1-y2; 
    int slope = 1; 
    if (y1 == y2 ) 
    { 
     slope = 0; 
    } 
    else if ( x1 == x2) 
    { 
     slope = 2; // vertical lines have no slopes... 
    } 
    else 
    { 
     slope = (int)xdiff/ydiff; 
    } 

    if (slope <= 1) 
    {  
     int startx = 0; 
     int endx = 0; 
     if (x1 > x2) 
     { 
      startx = x2; 
      endx = x1; 
     } 
     else 
     { 
      startx = x1; 
      endx = x2; 
     } 

     float y = y1; // initial value 
     for(int x = startx; x <= endx; x++) 
     { 
      y += slope; 
      DrawPixel(x, (int)abs(y), color); 
     } 
    } 

    else if (slope > 1) 
    { 
     float x = x1; // initial value 

     int starty = 0; 
     int endy = 0; 
     if (y1 > y2) 
     { 
      starty = y2; 
      endy = y1; 
     } 
     else 
     { 
      starty = y1; 
      endy = y2; 
     } 

     for(int y = starty; y <= endy; y++) 
     { 

      x += 1/slope; 

      DrawPixel((int)x, y, color); 
     } 

    } 

} 

回答

0

您不檢查x1 == x2和y1 == y2的情況,在這種情況下沒有行。另外,如果x,y和斜率是浮點數則更好。您可以通過以下方式更清楚地實現它。

void DrawLine(float x1, float y1, float x2, float y2, Color& color) 
{ 

    float xdiff = x2-x1; 
    float ydiff = y2-y1; 
    float dx, dy; // change in x & y at each iteration. 
    float slope = 1; // slope should be a float or a double. 
    int numOfSteps = 0; 
    if (y1 == y2 ) 
    { 
     if (x1 == x2) // error! not a line. 
      return; 
     slope = 0; 
     dx = 1; 
     dy = 0; 
     numOfSteps = xdiff/dx; 
    } 
    else if ( x1 == x2) 
    { 
     slope = 2; // vertical lines have no slopes... 
     dx = 0; 
     dy = 1; 
     numOfSteps = ydiff/dy; 
    } 
    else 
    { 
     slope = ydiff/xdiff; // Sorry I have reversed the slope as usually its calculated this way. 
     dx = 1; 
     dy = slope*dx; 
     numOfSteps = (ydiff/dy > xdiff/dx) ? ydiff/dy : xdiff/dx; 
    } 

    for(int i = 0; i <= numOfSteps; i++) 
    { 
     DrawPixel(x1, y1, color); 
     x1 += dx; 
     y1 += dy; 
    } 

} 
+0

對不起,但是,我認爲這不是DDA算法。這必須是Brasenham的算法。 – anonymous