Drawing Lines – The Bresenham Algorithm
Graphics Tutorial
By Hexar
Introduction
A line segment is defined by an infinite set of points which lie between two points;
these points have no area.
A problem occurs, however, when drawing lines on a
computer screen, namely that we have to approximate the line with pixels which
are not infinitely small,
and which are limited to fixed positions based on the
screen resolution.
Problem
It’s relatively easy to create an algorithm to generate the set of points which
approximate a line based on some floating point math:
void draw_line(int x1, int y1, int x2, int y2)
{
int dx = x2 – x1;
int dy = y2 – y1;
float m = dy/dx;
for (int x = x1; x < x2; x++)
{
int y = m*x + y1 + 0.5;
putpixel(x, y);
}
}
Figure 1. Floatingpoint linedrawing algorithm
This algorithm, of course, relies on some assumptions such as:
•
Noninfinite slope
•
x1 < x2
•
y1 < y2
But, for the most part, it works.
So what’s the problem? Any hardcore game
programmer will tell you:
Speed.
The Bresenham / Midpoint Algorithm is a solution that not only correctly picks
these same points, it does it with integer math only, which results in a big speed
improvement.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentApproximating Pixels
Let’s say we want to draw a line between two points, and that we will always
draw pixels on the endpoints.
Let us assume that the slope m follows
1
0
≤
≤
m
,
and that x1 < x2.
Figure 2. Selecting pixels based on midpoints
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '08
 SATHYANARAYA
 Computer Graphics, Negative and nonnegative numbers, blue line, Midpoint

Click to edit the document details