CG 2
CG 2
CG 2
Points and line segments are the simplest geometric components of pictures. Additional output
primitives that can be used to construct a picture include circles and other conic sections, quadric
surfaces, spline curves and surfaces, polygon color areas, and character strings
Line drawing is accomplished by calculating intermediate positions along the line path between
two specified endpoint positions. An output device is then directed to fill in these positions
between the endpoints.
Digital devices display a straight line segment by plotting discrete points between the two
endpoints. Discrete coordinate positions along the line path are calculated from the equation of
the line.
For a raster video display, the line color (intensity) is then loaded into the frame buffer at the
corresponding pixel coordinates. Reading from the frame buffer, the video controller then plots
the screen pixels. Screen locations are referenced with integer values, so plotted positions may
only approximate actual line positions between two specified endpoints.
Bekretsyon B. Page 1
Simple Drawing Algorithms
For example, a computed line position of (10.48, 20.51) would be converted to pixel position
(10, 21). Thus rounding of coordinate values to integers causes lines to be displayed with a stair
step appearance ("the jaggies").
The characteristic stair step shape of raster lines is particularly noticeable on systems with low
resolution, and we can improve their appearance somewhat by displaying them on high
resolution systems.
From these relations for any given x interval Δx along a line, we can compute the corresponding
y interval Δy as:
Δy = mΔx
Similarly, we can obtain the x interval Δx corresponding to a specified Δy as:
𝚫𝐲
Δx = 𝐦
These equations are the basis for drawing lines using plotted pixels.
Bekretsyon B. Page 2
Simple Drawing Algorithms
If the absolute value of a negative slope > 1, sample at a negative unit interval (Δy = -1)
and determine x, i.e. Δx = − 1⁄𝑚
i.e. 𝑦𝑖+1 = 𝑦𝑖 − 1, 𝑥𝑖+1 = 𝑥𝑖 − 1⁄𝑚
Note that:
1. Subscript i takes integer values from 1 for first point and increases by 1 until the final
endpoint is reached.
2. Since m can be any real number in the given slope interval, the calculated x or y values must
be rounded to the nearest integer
This algorithm is summarized in the following procedure, which accepts as input the two
endpoint pixel positions.
Horizontal and vertical differences between endpoint positions are assigned to parameters dx and dy.
The difference with the greater magnitude determines the value of parameter steps
Starting with pixel position (xa, ya), we determine the offset needed at each step to generate the next
pixel position along the line path
We loop through this process steps times
If the magnitude of dx is greater than the magnitude of dy and xa is less than xb, the values of the
increments in the x and y directions are 1 and m, respectively
If the greater change is in the x direction, but xa is greater than xb, then the decrements - 1 and -m are
used to generate each new point on the line
Otherwise, we use a unit increment (or decrement) in the y direction and an x increment (or
decrement) of 1 / m.
int round(float a)
{
return ((int) (a + 0.5));
}
void lineDDA(int xa, int ya, int xb, int yb)
{
int dx = xb - xa, dy = yb - ya, steps, i;
float xIncrement, yIncrement, x = xa, y = ya;
if (abs(dx) > abs(dy))
steps = abs(dx);
else
steps = abs(dy);
xIncrement = dx / (float) steps;
yIncrement = dy / (float) steps;
putpixel(round(x), round(y), WHITE);
for (i = 0; i < steps; i++)
{
x += xIncrement;
Bekretsyon B. Page 3
Simple Drawing Algorithms
y += yIncrement;
putpixel(round(x), round(y), WHITE);
}
}
Even if the DDA algorithm is a faster method for calculating pixel positions than the direct use
of line equation it has the following drawback.
The accumulation of round off error in successive additions of the floating-point
increment, which, causes the calculated pixel positions to drift away from the true line
path for long line segments.
The rounding operations and floating-point arithmetic in procedure lineDDA are still
time-consuming
The performance of DDA algorithm can be improved by separating the increments m and 1/m
into integer and fractional parts so that all calculations are reduced to integer operations.
2.5. Bresenham's Line Drawing Algorithm (Reading assignment)
This algorithm is an accurate and efficient raster line-generating algorithm developed by
Bresenham. It is scan conversion algorithm using only incremental integer calculations that can
be adapted to display circles and other curves.
A circle is defined as the set of points that are at a given distance r from center position (xc, yc).
This distance relationship is expressed by the Pythagorean Theorem in Cartesian coordinate as:
(x – xc)2 + (y – yc)2 = r2
We could use this equation to calculate the position of points on a circle circumference by
stepping along the x axis in unit steps from xc - r to xc + r and calculating the corresponding y
values at each position as:
y = 𝑦𝑐 ± √𝑟 2 − (𝑥 − 𝑥𝑐 )2
But this is not the best method for generating a circle. One problem is that it involves
considerable computation at each step. Moreover, the spacing between plotted pixel positions is
not uniform.
2.6.2. Using Polar Coordinates
Another way of drawing a circle and eliminating the unequal spacing is using polar coordinates.
This is by calculating points along the circumference with r and θ (the angle). The polar equation
for the point (x, y) on the circular path is given by:
x = xc + r *cos θ, y = yc + r *sin θ
When a display coordinate is generated with these equations using a fixed angular step size θ, a
circle is plotted with equally spaced points along the circumference.
Computation can be reduced by considering the symmetry of circles. The shape of the circle is
similar in each quadrant. The similar equation can be used for ellipse.
x = xc + rx *cos θ, y = yc + ry *sin θ
where rx is semi-major axis and ry is semi-minor axis
An ellipse is defined as the set of points such that the sum of the distances from two fixed
positions (foci) is the same for all points.
2.6.3 Midpoint Circle Algorithm
As in the raster line algorithm, we sample at unit intervals and determine the closest pixel
position to the specified circle path at each step. For a given radius r and screen center position
(xc, yc), we can first set up our algorithm to calculate pixel positions around a circle path centered
at the coordinate origin (0, 0). Then each calculated position (x, y) is moved to its proper screen
position by adding xc to x and yc to y. Along the circle section from x = 0 to x = y in the first
quadrant, the slope of the curve varies from 0 to -1. Therefore, we can take unit steps in the
positive x direction over this octant and use a decision parameter to determine which of the two
Bekretsyon B. Page 5
Simple Drawing Algorithms
possible y positions is closer to the circle path at each step. Positions in the other seven octants
are then obtained by symmetry
Figure 2.1 Symmetry of a circle. Calculations of a circle point (x, y) in one octant yields the
circle shown for the other seven octants
To apply the midpoint method, we define a circle function:
fcircle(x, y) = x2 + y2 – r2
Any point (x, y) on the boundary of the circle with radius r satisfies the equation f circle(x, y) = 0.
If the point is in the interior of the circle, the circle function is negative. And if the point is
outside the circle, the circle function is positive.
The circle-function tests are performed for the mid positions between pixels near the circle path
at each sampling step. Thus, the circle function is the decision parameter in the midpoint
algorithm, and we can set up incremental calculations for this function.
Figure 2.2 Midpoint between candidate pixels at sampling position xk + 1 along a circular path
Figure 2.2 shows the midpoint between the two candidate pixels at sampling position xk + 1
Assuming we have just plotted the pixel at (xk, yk), we next need to determine whether the pixel
at position (xk + 1, yk) or the one at position (xk + 1, yk – 1) is closer to the circle.
Our decision parameter is the circle function evaluated at the midpoint between these two pixels:
1 1
pk = fcircle(xk + 1, yk – 2) = (xk + 1)2 + (yk – 2)2– r2
Bekretsyon B. Page 6
Simple Drawing Algorithms
If pk < 0, this midpoint is inside the circle and the pixel on scan line yk is closer to the circle
boundary. Otherwise, the mid position is outside or on the circle boundary, and we select the
pixel on scan line yk - 1
Successive decision parameters are obtained using incremental calculations. We obtain a
recursive expression for the next decision parameter by evaluating the circle function at sampling
position xk + 1 + 1 = xk + 2:
1
pk + 1 = fcircle(xk + 1 + 1, yk + 1 – 2)
1
= [(xk + 1) + 1]2 + (yk + 1 – 2)2 – r2
or
pk + 1 = pk + 2(xk + 1) + (𝑦𝑘+1
2
– 𝑦𝑘2 ) – (yk + 1 – yk ) + 1
where yk + 1 is either yk or yk – 1, depending on the sign of pk
Increments for obtaining pk + 1 are either 2xk + 1 + 1 (if pk is negative) or 2xk + 1 + 1 – 2yk + 1
Evaluation of the terms 2xk + 1 and 2yk + 1 can also be done incrementally as
2xk + 1 = 2xk + 2
2yk + 1 = 2yk – 2
At the start position (0, r), these two terms have the values 0 and 2r, respectively
Each successive value is obtained by adding 2 to the previous value 2x and subtracting 2 from
the previous value of 2y
The initial decision parameter is obtained by evaluating the circle function at the start position
(x0, y0) = (0, r):
1 1
p0 = fcircle(1, r – 2) = 1 + (r – 2)2 – r2
or
5
p0 = 4
–r
If the radius is specified as an integer, we can simply round p0 to 1 – r since all increments are
integers
We can summarize the steps in the midpoint circle algorithm as follows:
1. Input radius r and circle center (xc, yc), and obtain the first point on the circumference of a
circle centered on the origin as
(x0, y0) = (0, r)
2. Calculate the initial value of the decision parameter as:
Bekretsyon B. Page 7
Simple Drawing Algorithms
5
p0 = 4
–r
3. At each xk position, starting at k = 0, perform the following test: if pk < 0, the next point
along the circle centered on (0, 0) is (xk + 1, yk) and
pk + 1 = pk + 2xk + 1 + 1
Otherwise, the next point along the circle is (xk + 1, yk – 1) and
pk + 1 = pk + 2xk + 1 + 1 – 2yk + 1
where 2xk+1 = 2xk + 2 and 2yk+1 = 2yk - 2
4. Determine symmetry points in the other seven octants.
5. Move each calculated pixel position (x, y) onto the circular path centered on (xc, yc) and plot
the coordinate values:
x = x + xc ,
y = y + yc
6. Repeat steps 3 through 5 until x ≥ y
An implementation of midpoint circle algorithm is given below:
void circleMidpoint(int xCenter, int yCenter, int radius)
{
int x = 0, y = radius;
int p = 1 - radius;
circlePlotPoints(xCenter, yCenter, x, y);
while (x < y)
{
x++;
if (p < 0)
p += 2 * x + 1;
else
{
y--;
p += 2 * (x - y) + 1;
}
circlePlotPoints(xCenter, yCenter, x, y);
}
}
void circlePlotPoints(int xCenter, int yCenter, int x, int y)
{
putpixel(xCenter + x, yCenter + y, WHITE);
putpixel(xCenter - x, yCenter + y, WHITE);
putpixel(xCenter + x, yCenter - y, WHITE);
putpixel(xCenter - x, yCenter - y, WHITE);
putpixel(xCenter + y, yCenter + x, WHITE);
putpixel(xCenter - y, yCenter + x, WHITE);
Bekretsyon B. Page 8
Simple Drawing Algorithms
A simple method for representing the character shapes in a particular typeface is to use
rectangular grid patterns. The set of characters are then referred to as a bitmap font.
Another, more flexible, scheme is to describe character shapes using straight-line and curve
sections, as in PostScript, for example. In this case, the set of characters is called an outline font.
When the pattern in Figure 2.3 (a) is copied to an area of the frame buffer, the 1 bits designate
which pixel positions are to be displayed on the monitor. To display the character shape in
Figure 2.3 (b), the interior of the character outline must be filled using the scan-line fill
procedure.
Bekretsyon B. Page 9
Simple Drawing Algorithms
Figure 2.3 The letter B represented in (a) with an 8 by 8 bi-level bitmap pattern and in
(b) with an outline shape defined with straight-line and curve segments
2.9 Region Filling Algorithms
In graphics drawing, a region is given by a set of pixels or boundary of the region. In order to
provide the drawing with the color of interest, from different algorithms here we discuss two
basic methods, namely boundary fill and flood fill.
2.9.1 Boundary-Fill Algorithm
A boundary-fill algorithm accepts as input the coordinates of an interior point (x, y), a fill color,
and a boundary color. Starting from (x, y), the procedure tests neighboring positions to determine
whether they are of the boundary color. If not, they are painted with the fill color, and their
neighbors are tested. This process continues until all pixels up to the boundary color for the area
have been tested. The designer can choose the fill color to be the same as the boundary color.
There are two methods used to paint neighboring pixels from the current position 4-connected
and 8-conneted.
4-connected 8-connected
In area filling 4-connected method four neighboring pixels are tested. These are the pixel
positions that are right, left, above, and below the current pixel.
8-connected area filling method is used to fill more complex figures. Here the set of neighboring
positions to be tested includes the four diagonal pixels.
The following function illustrates a recursive method for 4-connected boundary fill.
void boundaryFill4 (int x, int y, int fill, int boundary)
{
int current;
current = getpixel (x, y);
if ((current != boundary) && (current != fill))
{
putpixel(x, y, fill);
boundaryFill4 (x+1, y, fill, boundary);
boundaryFill4 (x-1, y, fill, boundary);
boundaryFill4 (x, y+1, fill, boundary);
boundaryFill4 (x, y-1, fill, boundary);
}
}
2.9.2 Flood-Fill Algorithm
Bekretsyon B. Page 10
Simple Drawing Algorithms
Sometimes we want to fill in (or recolor) an area that is not defined within a single color
boundary. We can paint such areas by replacing a specified interior color instead of searching for
a boundary color value. This approach is called a flood-fill algorithm.
We start from a specified interior point (x, y) and reassign all pixel values that are currently set to
a given interior color with the desired fill color. If the area we want to paint has more than one
interior color, we can first reassign pixel values so that all interior points have the same color.
Using either a 4-connected or 8-connected approach, we then step through pixel positions until
all interior points have been repainted. The following procedure flood fills a 4-onnected region
recursively, starting from the input position.
void floodFill4( int x, int y, int fillcolor , int oldcolor)
{
if(getpixel(x, y) == oldcolor)
{
putpixel(x, y,fillcolor);
floodFill4 ( x + 1 , y, fillcolor, oldcolor);
floodFill4 (x-1, y, fillcolor, oldcolor);
floodFill4 (x, y + 1, fillcolor, oldcolor);
floodFill4(x , y-1, fillcolor, oldcolor);
}
}
2.10 Graphics Functions
arc - is used to draw an arc. Syntax: arc(Xcenter, Ycenter, Start_Angle, End_Angle, Radius);
bar - Bar function is used to draw a 2-dimensional, rectangular filled in bar. Syntax:
bar(left, top, right, bottom);
bar3d – bar3d function is used to draw a 3-dimensional, rectangular filled in bar. Syntax:
bar3d(left, top, right, bottom, depth, topflag);
circle – used to draw circle. Syntax: Circle(Xcenter, Ycenter, Radius)
cleardevice - clears the screen in graphics mode and sets the current position to (0,0). Syntax: Cleardevice()
closegraph - closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen
to the mode it was in before you called initgraph. Syntax: Closegraph()
drawpoly - used to draw polygons i.e. triangle, rectangle, pentagon, hexagon etc. Syntax:
drawpoly( num, *points ); where num = (n+1) number of points for n – vertices & points = a
sequence of (n*2) integers. Each pair of integers gives x and y coordinates of a point on the polygon.
ellipse - used to draw an ellipse. Syntax:
ellipse(Xcenter, Ycenter, Start_Angle, End_Angle, xradius, yradius);
fillellipse – fillellipse(xcenter, ycenter, xradius, yradius) -
fillpoly - draws and fills a polygon. Syntax: fillpoly( int num, int *polypoints );
floodfill - used to fill an enclosed area. Syntax: floodfill(int x, int y, int border);
getarccords - used to get coordinates of arc which is drawn most recently. Syntax:
getarccoords(struct arccoordstype *var);
getbkcolor -returns the current background color. Syntax: getbkcolor();
Bekretsyon B. Page 11
Simple Drawing Algorithms
Bekretsyon B. Page 12
Simple Drawing Algorithms
Summary Questions
A. Fill in the blank space
1. The basic elements constituting a geometric structures are called __________
2. ________ function in C++ is used to plot a point on CRT monitor.
3. ___________clears the screen in graphics mode and sets the current position to (0,0).
4. _________ closes the graphics mode, deallocates all memory allocated by graphics system and
restores the screen
5. ________ display text or string at a specified point(x,y) on the screen.
B. Say true or false
1. Scan-converting algorithms use pixel to create basic pictures.
2. getx() function returns the maximum X coordinate of current graphics
3. In DDA line algorithms, calculated pixel positions drift away from the true line path due to the
accumulated round-off error in successive additions of the floating-point increment.
4. DDA algorithm is used to construct only lines.
5. setbkcolor() function returns the current background color.
C. Answer Accordingly
1. Write a program that draws a line from the origin to a point (350, 250) using a) DDA algorithm b)
built-in line function.
2. Write a program that draws 10 concentric circles center at (200,200) with different color
3. Write a program that draws a circle of radius 50 and center (200,200) using midpoint algorithm.
4. Using arc graphics function draw a circle of radius 80 centered at (250, 300) and fill with red color.
5. Write a program that draws 6-sided polygon and fill with green color using boundary fill algorithm.
6. Write a program that draws letter “B” using lines and curves.
7. Using sector graphics function draw an ellipse and fill with green color by flood fill algorithm.
8. Using output primitive line draw triangle, rectangle and square of any size and fill with color.
9. Write a program that draws an ellipse at the midpoint of your window with major-axis 100 and
minor-axis 50.
10. Using output primitives line, circle and ellipse draw a 2-d house (‘Sar bet’) include all parts and fill
parts with color using flood fill algorithm.
11. Draw a simple 2D person standing proudly. Use region filling algorithm to decorate the picture.
12. Write a procedure or function for 8-conneted boundary and flood fill algorithms.
Bekretsyon B. Page 13