DDA Line Drawing Algorithm

Description: DDA Digital Differential Analyzer Walk through the line, starting at (x0,y0) Constrain x, y increments to values in [0,1] range Case a: x is incrementing faster (m < 1) Step in x=1 increments, compute and round y Case b: y is incrementing faster (m > 1) Step in y=1 increments, compute and round x A line algorithm based on calculating either Δy or Δx using the above equations. There are two cases: 1)Negative slope 1)DDA Algorithm (Positive Slope) If m ≤ 1 then take Δx = 1 Compute successive y by yk+1 = yk + m -----(1) Subscript k takes integer values starting from 1, for the first point, and increases by 1 until the final end point is reached. If m > 1, reverse the role of x and y and take Δy = 1, calculate successive x from xk+1 = xk + 1/m ------(2) In this case, each computed x value is rounded to the nearest integer pixel position. The above equations are based on the assumption that lines are to be processed from left endpoint to right endpoint. 2)DDA Algorithm (Negative Slope) In case the line is processed from Right endpoint to Left endpoint, then Δx = −1, yk+1 = yk − m for m ≤ 1 ---------(3) or Δy = −1, xk+1 = xk −1/m for m > 1 ---------(4) Now, If m < 1, use(1) [provided line is calculated from left to right] and use(3) [provided line is calculated from right to left]. If m ≥ 1 use (2) or (4). Algorithm:DDA Procedure lineDDA(xa,ya,xb,yb:integer); Var dx,dy,steps,k:integer xIncrement,yIncrement,x,y:real; begin dx:=xb-xa; dy:=yb-ya; if abs(dx)>abs(dy) then steps:=abs(dx) else steps:=abs(dy); xIncrement:=dx/steps; yIncrement:=dy/steps; x:=xa; y:=ya; setPixel(round(x),round(y),1); for k:=1 to steps do begin x:=x+xIncrement; y:=y+yIncrement; setPixel(round(x),round(y),1) end end; {lineDDA} C Program For DDA Line Drawing Algorithm Source Code: #include <graphics.h> #include <stdio.h> #include <math.h> #include <conio.h> void ddaLine(int x1,int y1,int x2,int y2) { float x=x1,y=y1,dx,dy; int length,i; putpixel(x1,y1,WHITE); if(abs(x2-x1)>=abs(y2-y1)) length=abs(x2-x1); else length=abs(y2-y1); dx=(float)(x2-x1)/length; dy=(float)(y2-y1)/length; for(i=1;i<=length;i++) { x=x+dx; y=y+dy; putpixel((int)x,(int)y,WHITE); } } void main() { int x1,y1,x2,y2; int gdriver = DETECT, gmode; initgraph(&gdriver, &gmode, "c:/tc/bgi"); printf("Enter the starting co-ordinates: "); scanf("%d %d",&x1,&y1); printf("Enter the ending co-ordinates: "); scanf("%d %d",&x2,&y2); ddaLine(x1,y1,x2,y2); getch(); }

Share:

1 comments