This blog is under construction

Saturday, 31 August 2013

C program to implement dda line drawing algorithm

DDA refers to Digital Differential Analyzer.

DDA Line Drawing Algorithm:
Step 1:  Get the endpoints of a line from the user.
             (Xstart, Ystart)  and (Xend, Yend) are the end points of a line.

Step 2:  Calculate dx and dy.
             dx = Xend - Xstart
             dy = Yend - Ystart

Step 3:  Calculate the slope 'm'
             m = dx / dy;

Step 4:  If slope is less than or equal to 1(| m |  <= 1), then the X and Y successors are calculated as follows.
             Xk + 1 = Xk + 1
             Yk + 1 = Yk + m
k starts from 1 and get incremented by 1 until endpoint(Xend) is reached.

Step 5:  If slope is greater than 1(| m | > 1), then the X and Y successors are calculated as follows.
             Yk + 1 = Yk + 1
             Xk + 1 = Xk + (1 / m)
k starts from 1 and get incremented by 1 until endpoint(Yend) is reached.


Write a C program to implement DDA line drawing algorithm:


  #include <stdio.h>
  #include <conio.h>
  #include <graphics.h>
  #include <math.h>
  #include <dos.h>

  int main() {
        /* request auto detection */
        int gdriver = DETECT, gmode, err;
        int i, x1, y1, x2, y2, dx, dy, steps;
        float x, y, xincr, yincr;

        /* initialize graphic mode */
        initgraph(&gdriver, &gmode, "C:/TURBOC3/BGI");

        err = graphresult();

        if (err != grOk) {
                /* error occurred */
                printf("Graphic Error: %s\n",
                                grapherrormsg(err));
                getch();
                return 0;
        }

        /* draw line from (0, 0) to x-axis & y-axis maximum */
        x1 = y1 = 0;
        x2 = getmaxx(), y2 = getmaxy();

        dx = x2 - x1;
        dy = y2 - y1;

        x = x1, y = y1;

        steps = abs(dx) > abs(dy) ? dx : dy;

        xincr = (1.0 * dx) / steps;
        yincr = (1.0 * dy) / steps;

        putpixel((int) x, (int) y, WHITE);

        /* find the x and y successors and plot the pixels */
        for (i = 0; i < steps; i++) {
                x = x + xincr;
                y = y + yincr;

                /* put a pixel at the given postion(x, y) */
                putpixel((int) x, (int) y, WHITE);

                /* sleep for 50 milliseconds */
                delay(50);
        }

        /* deallocate memory allocated fro graphic screen */
        closegraph();
        return 0;
  }



Output: (DDA line drawing algorithm)


3 comments:

  1. please make it simple.....it use lots of memory and time...and also have a long code.

    ReplyDelete