Pergunta

My code for implementation of DDA (Digital Differential Analyzer) algorithm is working good for drawing lines with slope less than 45o but fails in lines slope more than 45o.

It is behaving like a broken line for angles > 45o


Code

void dda(int x1,int y1,int x2,int y2)
{
    float x,y,xinc,yinc,dx,dy;
    int k,step;
    dx = x2 - x1;
    dy = y2 - y1;
    step = abs(dx);
    xinc = dx / step;
    yinc = dy / step;
    x = x1;
    y = y1;
    putpixel(x,y,63);
    for(k=1;k<=step;k++)
    {
        x = x + xinc;
        y = y + yinc;
        putpixel(x,y,63);
    }
}

Is this the demerit of DDA algorithm or there is any fault in my code, please help me to find out the cause that is making my program inefficient.
Thanks

Foi útil?

Solução 3

No, There is no such demerit in DDA algorithm, you should use the following code, It will definitely work.
It will be better if you use Bresenham's line Drawing Algorithm.

You are only using dx to calculate unit step for your algorithm, thus it draws lines with angle < 45o.
You are not using dy in your program code for slope > 45o that is why your lines becomes broken. Append this code, and your code will work fine.

   if(abs(dx)>abs(dy))
       step=abs(dx);
   else
       step=abs(dy);

Outras dicas

If you want to draw lines with a slope > 1, you have to iterate over the y-value. This is natural since there are more steps in the y-direction than there are in the x-direction.

As Wikipedia says:

Considering a line with positive slope, if the slope is less than or equal to 1, we sample at unit x intervals ...

...

For lines with slope greater than 1, we reverse the role of x and y ...

So, there's your answer. You need to have an if, checking the slope and fixing either dx or dy to 1. See the Wikipedia link I put above for more details.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top