2013-09-29 5 views
0

라인이 세로 1. 가로 2. 세로 3. 경사가 1보다 작은 모든 사례를 테스트했습니다. 이 함수는 작동하지만 오버 플로우가 발생하면 테스트 케이스를 잃어버린 것처럼 검토하고 싶습니다. 방금 위키 백과에서 알고리즘을 읽고 wikipedia 기사에서 알고리즘을 구현하려고했습니다.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