Skip to content

Instantly share code, notes, and snippets.

@gldraphael
Created September 25, 2015 20:33
Show Gist options
  • Save gldraphael/105fd0723b902f0ecfa5 to your computer and use it in GitHub Desktop.
Save gldraphael/105fd0723b902f0ecfa5 to your computer and use it in GitHub Desktop.
Simple Line Drawing Algorithm using graphics.h
#include <iostream.h>
#include <math.h>
#include <conio.h>
#include <graphics.h>
#include <dos.h>
int sign(float args)
{
if (args < 0)
return -1;
else if (args > 0)
return 1;
else return 0;
}
void main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\turboc3\\bgi");
int x, y, x1, y1;
float l, dx, dy, xinc, yinc;
cout << "Enter starting co ordinates (x, y): ";
cin >> x >> y;
cout << "Enter ending co ordinates (x, y): ";
cin >> x1 >> y1;
// Set length as x1-x or y1-y, whatever is greater
l = abs(x1 - x) > abs(y1 - y) ? abs (x1 - x) : abs (y1 - y);
// Calculate delta(x) and delta(y)
dx = (x1 - x)/l;
dy = (y1 - y)/l;
xinc = x + 0.5 * sign(dx);
yinc = y + 0.5 * sign(dy);
for (int i = 0; i <= l; i ++)
{
putpixel(abs(xinc), abs(yinc), WHITE);
xinc = abs (xinc + dx);
yinc = abs (yinc + dy);
}
getch();
closegraph();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment