DDA abbreviated for Digital Differential Analyzer has very simple technique. Find difference dx and dy between x coordinates and y coordinates respectively ending points of a line. If |dx| is greater than |dy|, than |dx| will be step and otherwise |dy| will be step.

  
if |dx|>|dy| then   
Step = |dx|                                   
else
         Step = |dy|


Now very simple to say that Step is the total number of pixel required for a line.Next step is to divide dx and dy by step to get xIncrement and yIncrement that is the increment required in each step to find next pixel value.



xIncrement = dx/step      

yIncrement = dy/step



Next a loop is required that will run step times. In the loop drawPixel and add xIncrement in x1 by and yIncrement in y1.


#include<stdio.h>
#include<graphics.h>
#include<stdlib.h>
#include<io.h>
#include<conio.h>
#include<ctype.h>
#include<dos.h>
#define ROUND(a) ((int)(a+0.5))

/* **************************************************** */
/* C Program for Drowing Line */
/* Digital Differential Analyzer */
/* Written By: Ritesh Kumar Jain */
/* **************************************************** */

void setpixel(int,int);
 
void main()
{

       //function prototype
       void lineDDA(int, int, int, int);

       int graphdriver;
       int graphmode;
       int x1,y1,x2,y2;

       printf(" ********* WELCOME********* \n\n ");
       printf(" Plze enter the start and end points \n ");

       printf("x1= "); scanf("%d",&x1);
       printf("\ny1= "); scanf("%d",&y1);
       printf("\nx2= "); scanf("%d",&x2);
       printf("\ny2= "); scanf("%d",&y2);

       graphdriver= DETECT;
       initgraph(&graphdriver, &graphmode," \\tc\BGI");

       setpalette(0,4);
       setbkcolor(0);

       lineDDA(x1,y1,x2,y2);

}//end of main

void lineDDA(int xa, int ya, int xb, int yb)
{

      int dx=xb-xa, dy=yb-ya, steps, k;
      float xIncrement, yIncrement, x=xa, y=ya;
 
      if(abs(dx)>abs(dy))
           steps=abs(dx);
      else
           steps=abs(dy);

      xIncrement = dx/(float) steps;
      yIncrement = dy/(float) steps;
 
      setpixel(ROUND(x),ROUND(y));
 
      for(k=0;k<steps;k++)
      {
            x += xIncrement;
            y += yIncrement;
            setpixel(ROUND(x),ROUND(y));
      }

      getch();
}


void setpixel(x,y)
int x,y;
{
      putpixel(x,480-y,RED);
}

0 comments