Author Topic: VC++ - Bresenham Line Drawing Algorithm (text mode output of line)  (Read 2952 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
The source code for Bresenham Line Algorithm is given here.

The formula is,

y = m * (x - x0) + y0

where m = slope (y1 - y0) / (x1 - x0)
x0 and y0 are the starting points
x is the next x axis point in the loop
y is the corresponding y axis point to the x

Code: (C++)
//Source Code Listing


#include <iostream>
#include <windows.h>


void gotoxy(int x, int y)
{
   COORD ord;
   ord.X = x;
   ord.Y = y;
   SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), ord);
}

void Draw_Line(int left, int top, int right, int bottom)
{
   // Bresenham Line Algorithm
   // y = m * (x - x0) + y0
   // where m = slope
   // x0 and y0 are the starting points
   // x is the next x axis point in the loop
   // y is the corresponding y axis point to the x

   double m = ((double) bottom - top) / ((double) right - left);
   for(int x = left; x <= right; x++)
   {
      int y = m * (x - left) + top;
      gotoxy(x, y);
      std::cout << "x";
   }

}

void main()
{
   Draw_Line(10,10,20,20);
   Draw_Line(10,20,20,10);

   Draw_Line(30,0,60,20);
   Draw_Line(30,20,60,0);

   gotoxy(0,0);
}





 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1