Bresenham’s Line Drawing Algorithm

On October 7, 2008, in Algorithms, by , Views : 12107


The Bresenham line algorithm is an algorithm which determines which points in an n-dimensional raster should be plotted in order to form a close approximation to a straight line between two given points. It is commonly used to draw lines on a computer screen, as it uses only integer addition, subtraction and bit shifting, all of which are very cheap operations in standard computer architectures. It is one of the earliest algorithms developed in the field of computer graphics. A minor extension to the original algorithm also deals with drawing circles. For more info on the algorithm, see Bresenham’s line algorithm.

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
 
void swap(int &x, int &y)
{
    int k = x;
    x = y;
    y = k;
}
 
void main()
{
    int gd = DETECT, gm = DETECT, x1, x2, y1, y2, dx, dy, p, k;
    float m = 0;
 
    clrscr();
 
    printf("Enter the sarting point x1 & y1\n");
    scanf("%d%d", &x1, &y1);
 
    printf("Enter the end point x2 & y2\n");
    scanf("%d%d", &x2, &y2);
 
    dx = abs(x2 - x1);
    dy = abs(y2 - y1);
    m = (float) (y2 - y1) / (x2 - x1);
 
    initgraph(&gd, &gm, "");
    cleardevice();
 
    if (fabs(m) > 1) {
	swap(x1, y1);
	swap(x2, y2);
	swap(dx, dy);
    }
 
    if ((x1 > x2)) {
	x1 = x2;
	y1 = y2;
    }
    p = 2 * dy - dx;
    for (k = 0; k < abs(dx); k++) {
	if (p < 0) {
	    p = p + 2 * dy;
	} else {
	    if (m < 0)
		y1--;
	    else
		y1++;
	    p = p + (2 * dy) - (2 * dx);
	}
	if (fabs(m) <= 1)
	    putpixel(x1++, y1, 15);
	else
	    putpixel(y1, x1++, 15);
    }
 
    getch();
}

Download the code using the below link:

Please 'Like' or '+1' us to get the download link! (If you have already liked us on facebook, then like us either on G+ or twitter)

Hope, it helps! 🙂



2 Responses to Bresenham’s Line Drawing Algorithm

  1. swapnil says:

    thanks again 🙂

  2. senthil says:

    nice

Leave a Reply

Your email address will not be published. Required fields are marked *


*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

  • Dipin Krishna

Archives

All entries, chronologically...

Read more:
BoundaryFill
Boundary Fill

wheel
Wheel

chess
Chess Board using DDA line drawing algorithm

MinMaxClose