Tuesday 21 July 2015

Line drawing using DDA algorithm in C

Program to draw a line using DDA Algorithm

Here's a program to draw a line in C language using DDL line drawing algorithm.
This program asks you for starting and ending co-ordinates of line and outputs an animation effect by drawing a line using DDA line drawing algorithm starting from the points given by user in the input .
Output Image will be something like this: 



Computer Graphics, DDA line drawing algorithm


#include <stdio.h>
#include <dos.h>
#include <graphics.h>
void lineDDA(int, int, int, int);
void main()
{
    int x1, y1, xn, yn;
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TurboC3\\BGI");
    printf("Enter the X Co-ordinate of starting point of line: ");
    scanf("%d", &x1);
    printf("Enter the Y Co-ordinate of starting point of line: ");
    scanf("%d", &y1);
    printf("Enter the X Co-ordinate of ending point of line: ");
    scanf("%d", &xn);
    printf("Enter the X Co-ordinate of ending point of line: ");
    scanf("%d", &yn);
    lineDDA(x1, y1, xn, yn);
    getch();
}

void lineDDA(int x1, int y1, int xn, int yn)
{
    int dx, dy, m, i;
    m = (yn-y1)/(xn-x1);

    for (i=x1; i<=xn; i++)
    {
        if (m <= 1)
        {
        dx = 1;
        dy = m * dx;
    }
    else
    {
        dy = 1;
        dx = dy / m;
}
x1 = x1 + dx;
y1 = y1 + dy;
putpixel(x1, y1, RED);
delay(20);
}
}

No comments:

Post a Comment