Wednesday, December 2, 2009

Line Drawing Algorithms

Line Algorithm
The basic algorithm works for lines which look like this:

o------- |
p1 -------- | deltaY
------- p2 |
-------o |

where p1 = (x1,y1),
p2 = (x2, y2),
x and y are both increasing from p1 to p2,
deltaX = x2 - x1,
deltaY = y2 - y1 and
deltaX >= deltay.

All other types of lines can be derived from this type. I'll get to this bit later.
First you need to perform the following intialisation:

x = x1
y = y1
d = (2 * deltaY) - deltaX

x is the current x location, you will add 1 to this variable after every pixel you draw until all pixels have been drawn. y is the current y location. The decision variable is used to determine when to add 1 to this value. d is the decision variable which will be used to keep a track of what to do.
Now you loop across the screen from x1 to x2 and for each loop perform the following operations for each pixel :

PutPixel(x, y); { Draw a pixel at the current point }
if d < 0 then
d := d + (2 * deltaY)
d := d + 2 * (deltaY - deltaX);
y := y + 1;
x := x + 1;

No comments:

Post a Comment