Computer Graphics
Computer Graphics
Introduction
Computer Graphics including digital images, animations, and interactive graphics used in
various sectors such as entertainment, education, scientific visualization, and virtual reality.
Computer Graphics can be used in UI design, rendering, geometric objects, animation, and
many more. In most areas, computer graphics is an abbreviation of CG.
1
10. Image Processing: Various kinds of photographs or images require editing in order to
be used in different places. Processing of existing images into refined ones for better
interpretation is one of the many applications of computer graphics.
2
Input Devices
The Input Devices are the hardware that is used to transfer transfers input to the computer. The
data can be in the form of text, graphics, sound, and text. Output device display data from the
memory of the computer. Output can be text, numeric data, line, polygon, and other objects.
1. Keyboard
2. Mouse
3. Trackball
4. Spaceball
5. Joystick
6. Light Pen
7. Digitizer
8. Touch Panels
9. Voice Recognition
10. Image Scanner
1. Keyboard:
The most commonly used input device is a keyboard. The data is entered by pressing the set of
keys. All keys are labeled. A keyboard with 101 keys is called a QWERTY keyboard.
The keyboard has alphabetic as well as numeric keys. Some special keys are also available
1. Numeric Keys: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2. Alphabetic keys: a to z (lower case), A to Z (upper case)
3. Special Control keys: Ctrl, Shift, Alt
4. Special Symbol Keys: ; , " ? @ ~ ? :
5. Cursor Control Keys: ↑ → ← ↓
6. Function Keys: F1 F2 F3....F9.
7. Numeric Keyboard: It is on the right-hand side of the keyboard and used for fast entry
of numeric data.
Function of Keyboard:
1. Alphanumeric Keyboards are used in CAD. (Computer Aided Drafting)
2. Keyboards are available with special features line screen co-ordinates entry, Menu
selection or graphics functions, etc.
3. Special purpose keyboards are available having buttons, dials, and switches. Dials are
used to enter scalar values. Dials also enter real numbers. Buttons and switches are used
to enter predefined function values.
Advantage:
1. Suitable for entering numeric data.
2. Function keys are a fast and effective method of using commands, with fewer errors.
Disadvantage:
1. Keyboard is not suitable for graphics input.
3
2. Mouse:
A Mouse is a pointing device and used to position the pointer on the screen. It is a small palm
size box. There are two or three depression switches on the top. The movement of the mouse
along the x-axis helps in the horizontal movement of the cursor and the movement along the y-
axis helps in the vertical movement of the cursor on the screen. The mouse cannot be used to
enter text. Therefore, they are used in conjunction with a keyboard.
Advantage:
1. Easy to use
2. Not very expensive
3. Trackball
It is a pointing device. It is similar to a mouse. This is mainly used in notebook or laptop
computer, instead of a mouse. This is a ball which is half inserted, and by changing fingers on the
ball, the pointer can be moved.
Advantage:
4. Spaceball:
It is similar to trackball, but it can move in six directions where trackball can move in two
directions only. The movement is recorded by the strain gauge. Strain gauge is applied with
pressure. It can be pushed and pulled in various directions. The ball has a diameter around 7.5
cm. The ball is mounted in the base using rollers. One-third of the ball is an inside box, the rest is
outside.
Applications:
4
5. Joystick:
6. Light Pen
Light Pen (similar to the pen) is a pointing device which is used to select a displayed menu item
or draw pictures on the monitor screen. It consists of a photocell and an optical system placed in
a small tube. When its tip is moved over the monitor screen, and pen button is pressed, its
photocell sensing element detects the screen location and sends the corresponding signals to the
CPU.
Uses:
In non-interactive computer graphics, the picture is produced on the monitor, and the user does
not have any controlled over the image, i.e., the user cannot make any change in the rendered
image. One example of its Titles shown on T.V.
Non-interactive Graphics involves only one-way communication between the computer and the
user, User can see the produced image, and he cannot make any change in the image.
In interactive Computer Graphics user have some controls over the picture, i.e., the user can
make any change in the produced image. One example of it is the ping-pong game.
Interactive Computer Graphics require two-way communication between the computer and the
user. A User can see the image and make any change by sending his command with an input
device.
5
Advantages:
1. Higher Quality
2. More precise results or products
3. Greater Productivity
4. Lower analysis and design cost
5. Significantly enhances our ability to understand data and to perceive trends.
monitor.
Frame Buffer: A digital frame buffer is large, contiguous piece of computer memory used to
hold or map the image displayed on the screen.
o At a minimum, there is 1 memory bit for each pixel in the raster. This amount of memory is
called a bit plane.
o A 1024 x 1024 element requires 220 (210=1024;220=1024 x 1024)[Link] or 1,048,576
memory bits in a single bit plane.
o The picture is built up in the frame buffer one bit at a time.
o ∵ A memory bit has only two states (binary 0 or 1), a single bit plane yields a black and
white (monochrome display).
o As frame buffer is a digital device write raster CRT is an analog device.
6
Display technology
Display technology is the use of visual displays to create images, and it is an important part of
computer graphics. Some of the most common display technologies used in computer monitors
include:
• Liquid Crystal Displays (LCD): A popular choice due to its affordability
• Light-emitting diodes (LED): A common display technology
• Organic Light Emitting Diodes (OLED): A high-end option that offers superior color and
contrast
Other display technologies include:
• Plasma Displays: Can generate high-quality images on large screens
• Field Emission Displays: Can produce high-resolution images without the bulk of a CRT
• Electronic Paper: Displays that are designed to mimic the look and feel of paper
• Digital Light Processing Technology (DLP): Uses microscopic mirrors to create large, bright
projections
Display technology is constantly evolving to meet the needs of society, and future displays are
expected to be lighter, thinner, more flexible, and more power efficient.
Once the electron heats the phosphorus, they light up, and they are projected on a screen. The
color you view on the screen is produced by a blend of red, blue and green light.
Components of CRT:
Main Components of CRT are:
1. Electron Gun: Electron gun consisting of a series of elements, primarily a heating
filament (heater) and a cathode. The electron gun creates a source of electrons which are
focused into a narrow beam directed at the face of the CRT.
2. Control Electrode: It is used to turn the electron beam on and off.
3. Focusing system: It is used to create a clear picture by focusing the electrons into a
narrow beam.
4. Deflection Yoke: It is used to control the direction of the electron beam. It creates an
electric or magnetic field which will bend the electron beam as it passes through the area.
In a conventional CRT, the yoke is linked to a sweep or scan generator. The deflection
yoke which is connected to the sweep generator creates a fluctuating electric or magnetic
potential.
5. Phosphorus-coated screen: The inside front surface of every CRT is coated with
phosphors. Phosphors glow when a high-energy electron beam hits them.
Phosphorescence is the term used to characterize the light given off by a phosphor after it
has been exposed to an electron beam.
7
Random Scan and Raster Scan Display:
Random Scan Display:
Random Scan System uses an electron beam which operates like a pencil to create a line image
on the CRT screen. The picture is constructed out of a sequence of straight-line segments. Each
line segment is drawn on the screen by directing the beam to move from one point on the screen
to the next, where its x & y coordinates define each point. After drawing the picture. The system
cycles back to the first line and design all the lines of the image 30 to 60 time each second. The
process is shown in fig:
Advantages:
1. A CRT has the electron beam directed only to the
parts of the screen where an image is to be drawn.
2. Produce smooth line drawings.
3. High Resolution
Disadvantages:
1. Random-Scan monitors cannot display realistic
shades scenes.
Frame Buffer is also known as Raster or bit map. In Frame Buffer the positions are called picture
elements or pixels. Beam refreshing is of two types. First is horizontal retracing and second is
vertical retracing. When the beam starts from the top left corner and reaches the bottom right
scale, it will again return to the top left side called at vertical retrace. Then it will again more
horizontally from top to bottom call as horizontal retracing shown in fig:
8
Types of Scanning or travelling of beam in Raster Scan
1. Interlaced Scanning
2. Non-Interlaced Scanning
In Interlaced scanning, each horizontal line of the screen is traced from top to bottom. Due to
which fading of display of object may occur. This problem can be solved by Non-Interlaced
scanning. In this first of all odd numbered lines are traced or visited by an electron beam, then in
the next circle, even number of lines are located.
For non-interlaced display refresh rate of 30 frames per second used. But it gives flickers. For
interlaced display refresh rate of 60 frames per second is used.
Advantages:
1. Realistic image
2. Million Different colors to be generated
3. Shadow Scenes are possible.
Disadvantages:
1. Low Resolution
2. Expensive
9
Advantages:
1. Inexpensive
Disadvantages:
1. Only four colors are possible
2. Quality of pictures is not as good as with another method.
2. Shadow-Mask Method:
o Shadow Mask Method is commonly used in Raster-Scan System because they produce a
much wider range of colors than the beam-penetration method.
o It is used in the majority of color TV sets and monitors.
Construction: A shadow mask CRT has 3 phosphor color dots at each pixel position.
10
Working: Triad arrangement of red, green, and blue guns.
The deflection system of the CRT operates on all 3 electron beams simultaneously; the 3 electron
beams are deflected and focused as a group onto the shadow mask, which contains a sequence of
holes aligned with the phosphor- dot patterns.
When the three beams pass through a hole in the shadow mask, they activate a dotted triangle,
which occurs as a small color spot on the screen.
The phosphor dots in the triangles are organized so that each electron beam can activate only its
corresponding color dot when it passes through the shadow mask.
Inline arrangement: Another configuration for the 3 electron guns is an Inline arrangement in
which the 3
electron guns and the corresponding red-green-blue color dots on the screen, are aligned along
one scan line rather of in a triangular pattern.
This inline arrangement of electron guns in easier to keep in alignment and is commonly used in
high-resolution color CRT's.
11
Advantage:
1. Realistic image
2. Million different colors to be generated
3. Shadow scenes are possible
Disadvantage:
1. Relatively expensive compared with the monochrome CRT.
2. Relatively poor resolution
3. Convergence Problem
Advantage:
1. No refreshing is needed.
2. High Resolution
3. Cost is very less
Disadvantage:
1. It is not possible to erase the selected part of a picture.
2. It is not suitable for dynamic graphics applications.
3. If a part of picture is to modify, then time is consumed.
12
Example: Small T.V. monitor, calculator, pocket video games, laptop computers, an
advertisement board in elevator.
1. Emissive Display: The emissive displays are devices that convert electrical energy into light.
Examples are Plasma Panel, thin film electroluminescent display and LED (Light Emitting
Diodes).
2. Non-Emissive Display: The Non-Emissive displays use optical effects to convert sunlight or
light from some other source into graphics patterns. Examples are LCD (Liquid Crystal Device).
Emissive Display:
1) Plasma Panel Display:
Plasma-Panels are also called as Gas-Discharge Display. It consists of an array of small lights.
Lights are fluorescent in nature. The essential components of the plasma-panel display are:
1. Cathode: It consists of fine wires. It delivers negative voltage to gas cells. The voltage is
released along with the negative axis.
2. Anode: It also consists of line wires. It delivers positive voltage. The voltage is supplied
along positive axis.
3. Fluorescent cells: It consists of small pockets of gas liquids when the voltage is applied
to this liquid (neon gas) it emits light.
4. Glass Plates: These plates act as capacitors. The voltage will be applied, the cell will
glow continuously.
The gas will slow when there is a significant voltage difference between horizontal and vertical
wires. The voltage level is kept between 90 volts to 120 volts. Plasma level does not require
refreshing. Erasing is done by reducing the voltage to 90 volts.
Each cell of plasma has two states, so cell is said to be stable. Displayable point in plasma panel
is made by the crossing of the horizontal and vertical grid. The resolution of the plasma panel can
be up to 512 * 512 pixels.
Figure shows the state of cell in plasma panel display:
13
Advantage:
1. High Resolution
2. Large screen size is also possible.
3. Less Volume
4. Less weight
5. Flicker Free Display
Disadvantage:
1. Poor Resolution
2. Wiring requirement anode and the cathode is complex.
3. Its addressing is also complex.
In an LED, a matrix of diodes is organized to form the pixel positions in the display and picture
definition is stored in a refresh buffer. Data is read from the refresh buffer and converted to
voltage levels that are applied to the diodes to produce the light pattern in the display.
Non-Emissive Display
1) LCD (Liquid Crystal Display):
Liquid Crystal Displays are the devices that produce a picture by passing polarized light from the
surroundings or from an internal light source through a liquid-crystal material that transmits the
light.
LCD uses the liquid-crystal material between two glass plates; each plate is the right angle to
each other between plates liquid is filled. One glass plate consists of rows of conductors arranged
in vertical direction. Another glass plate is consisting of a row of conductors arranged in
horizontal direction. The pixel position is determined by the intersection of the vertical &
horizontal conductor. This position is an active part of the screen.
Liquid crystal display is temperature dependent. It is between zero to seventy degree Celsius. It is
flat and requires very little power to operate.
14
Advantage:
1. Low power consumption.
2. Small Size
3. Low Cost
Disadvantage:
1. LCDs are temperature-dependent (0-70°C)
2. LCDs do not emit light; as a result, the image has very little contrast.
3. LCDs have no color capability.
4. The resolution is not as good as that of a CRT.
2) Look-Up Table:
Image representation is essentially the description of pixel colors. There are three primary colors:
R (red), G (green) and B (blue). Each primary color can take on intensity levels produces a
variety of colors. Using direct coding, we may allocate 3 bits for each pixel, with one bit for each
primary color. The 3-bit representation allows each primary to vary independently between two
intensity levels: 0 (off) or 1 (on). Hence each pixel can take on one of the eight colors.
0 0 0 Black
0 0 1 Blue
0 1 0 Green
0 1 1 Cyan
1 0 0 Red
1 0 1 Magenta
1 1 0 Yellow
1 1 1 White
A widely accepted industry standard uses 3 bytes, or 24 bytes, per pixel, with one byte for each
primary color. The way, we allow each primary color to have 256 different intensity levels. Thus
a pixel can take on a color from 256 x 256 x 256 or 16.7 million possible choices. The 24-bit
format is commonly referred to as the actual color representation.
Lookup Table approach reduces the storage requirement. In this approach pixel values do not
code colors directly. Alternatively, they are addresses or indices into a table of color values. The
color of a particular pixel is determined by the color value in the table entry that the value of the
pixel references. Figure shows a look-up table with 256 entries. The entries have addresses 0
through 255. Each entry contains a 24-bit RGB color value. Pixel values are now 1-byte. The
color of a pixel whose value is i, where 0 <i<255, is persistence by the color value in the table
entry whose address is i. It reduces the storage requirement of a 1000 x 1000 image to one
million bytes plus 768 bytes for the color values in the look-up table.
15
Random-Scan Display
In Random-Scan Display electron beam is directed only to the areas of screen where a picture has
to be drawn. It is also called vector display, as it draws picture one line at time. It can draw and
refresh component lines of a picture in any specified sequence. A Pen plotter is an example of
random-scan device. The number of lines regulates refresh rate on random-scan displays. An area
of memory called refresh display files stores picture definition as a set of line drawing
commands. The system returns back to first-line command in the list, after all the drawing
commands have been processed. High-quality vector systems can handle around 100, 00 short
lines at this refresh rate. Faster refreshing can burn phosphor. To avoid this every refresh cycle is
delayed to prevent refresh rate greater than 60 frames per second. Suppose we want to display a
square ABCD on the screen. The commands will be:
16
ADVANTAGES:
3) Higher resolution as compared to raster scan display.
4) Produces smooth line drawing.
5) Less Memory required.
DISADVANTAGES:
1) Realistic images with different shades cannot be drawn.
2) Colour limitations.
Raster-Scan Displays
Raster Scan Displays are most common type of graphics monitor which employs CRT. It is
based on television technology. In raster scan system electron beam sweeps across the screen,
from top to bottom covering one row at a time.A pattern of illuminated pattern of spots is
created by turning beam intensity on and off as it moves across each row. A memory area
called refresh buffer or frame buffer stores picture definition. This memory area holds intensity
values for all screen points. Stored intensity values are restored from frame buffer and painted
on screen taking one row at a [Link] screen point is referred to as pixels.
In raster scan systems refreshing is done at a rate of 60-80 frames per second. Refresh rates are
also sometimes described in units of cycles per second / Hertz (Hz). At the end of each scan
line, electron beam begins to display next scan line after returning to left side of screen. The
return to the left of screen after refresh of each scan line is known as horizontal retrace of
electron beam. At the end of each frame electron beam returns to top left corner and begins the
next frame.
17
Raster-Scan Display Processor:
An important function of display process is to digitize a picture definition given in an
application program into a set of pixel-intensity values for storage in refresh buffer. This
process is referred to as scan conversion. The purpose of display processors is to relieve the
CPU from graphics jobs.
Display processors can perform various other tasks like: creating different line styles,
displaying color areas, etc. Typically display processors are utilized to interface input devices,
such as mouse, joysticks.
ADVANTAGES:
1) Real life images with different shades can be displayed.
2) Color range available is bigger than random scan display.
DISADVANTAGES:
1) Resolution is lower than random scan display.
2) More memory is required.
3) Data about the intensities of all pixel has to be stored .
18
Graphics Functions in C
In graphics mode, we can display different effective text as well as we can draw different
graphical figures. By default, system is in text mode, but if we want to draw some graphical
figures, then we have to work in graphics mode. Once working in this mode is over, it is general
practice to close this mode. Some of the basic graphics functions are as follows:
A. Basic Graphics Mode Functions: -
1) initgraph(): - it is used to initialize graphics mode.
Syntax: initgraph(int driver, int mode, char path);
Where,
driver: This argument specifies the graphics driver to be used and it interfaces with display
adapter. Some of the available graphics driversare CGA, EGA, VGE, etc
mode: Each graphic adapter can use several different possible graphicsmodes. The mode
argument is used to select particular mode. Followingtable shows different possible modes for
CGA, VGA, EGA, etc.
Driver Selected Mode Constant Display Mode
CGA CGAC0 320x200, 4 color, palette
CGAC1 0320x200, 4 color, palette
CGAC2 1320x200, 4 color, palette
CGAC3 2320x200, 4 color, palette
CGSHI 3640x200, 2 color
EGA EGALO 640x200, 16 color
EGAHI 640x350, 16 color
VGA VGALO 640x200, 16 color
VGAMED 640x350, 16 color
VGAHI 640x480, 16 color
path: It specifies path to graphics driver. Graphics drivers are files with BGI file extension
supplies as part of Turbo C++. The path name is string therefore it must be surrounded by quotes.
Example:
initgraph(&gd, &gm,"C:\\TC\\BGI");
int gm, gd=DETECT;
where, gd specifies graphics [Link] specifies graphics mode.
“C: \\TC\\ BGI” specifies paths of BGI files
DETECT is macro which automatically selects the driver.
2) closegraph(): -
It is used to close graphics mode. When you exit from graphics mode, you should restore the
system to the previous display (text) mode. closegraph()function restores the previous display
mode. If you do not use this function and still you exit from graphics mode, system gives some
undesirable effects such as loss of cursor or off-sine characters. It is because system tries to write
text in graphics mode.
Syntax: closegraph();
B. Shapes:
Computer graphics has many in-built commands, which can be used either to draw a shape
and/or for filling a color in any bounded shape.
Following commands are available for drawing any basic shape and which aresupported by C
and C++:
19
3) lineto() : This command draws a line on screen from current cursor position to the(x,y)
position mentioned in command.
Syntax: lineto(x,y);
Where, (x,y) are co-ordinates of end point of line.
4) line(): -This command draws a line on screen.
Syntax: line(x1,y1,x2,y2);
Where, (x1,y1) are co-ordinates of starting point of line and (x2,y2) are co-ordinates of
end point of line.
Example: line(10,10,100,100);
5) circle(): -
This command draws a circle on screen.
Syntax: circle(x,y,r);
Where, (x, y) are co-ordinates of centre of circle and r is
radius of circle.
Example: circle(50,50,10);
It draws a circle with centre (50,50) and radius 10.
Output:
20
For full ellipse, the start and end should be 0 and 360 else it will draw an arcon screen.
Example: ellipse(100,100,0,360,20,10); Example: ellipse(100,100,0,360,10,20);
Where, n is number of vertices of a polygon+[Link] is integer array name which stores co-
ordinates of vertices of apolygon.
Example: drawpoly(4,m);
C. Colors:
9) setcolor(): - it draws any subsequent graphics in a color given in command.
Syntax: setcolor(color);
Where, pattern can be either pattern constant or patter name. These pattern constants are
given in following table.
Color is the color constant or color name.
Pattern Constant Pattern Name
0 EMPTY_FILL
1 SOLID_FILL
2 LINE_FILL
3 LTSLASH_FILL
21
4 SLASH_FILL
5 BKSLASH_FILL
6 LTBKSLASH_FILL
7 HATCH_FILL
8 XHATCH_FILL
9 INTELEAVE_FILL
10 WIDE_DOT_FILL
11 CLOSE_DOT_FILL
12 USER_FILL
11) setlinestyle(): - It specifies the thickness of the line to be drawn. These styles are notused for
the circles.
Syntax: setlinestyle(linestyle,user_defined_style,line_width);
Example: setlinestyle(2,0,3);
12) fillpoly(): - This command draws any polygon with n number of vertices and then fillit with
current setfillstyle.
Note: - drawpoly and fillpoly both commands draw a polygon with latest currentsetcolor and
setline style.
Syntax: fillpoly(n,array);
Where, n is number of vertices of a polygon + [Link] is integer array name which stores co-
ordinates of vertices of a polygon.
1) C program to draw arc in c graphics
#include <graphics.h>
#include <stdio.h>
int main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, “C\\tc\\bgi);
arc(150,150,90, 270,80);
getch();
22
closegraph();
return 0;
}
23
Unit: II Scan Conversion
Scan Conversion Definition
It is a process of representing graphics objects a collection of pixels. The graphics objects are
continuous. The pixels used are discrete. Each pixel can have either on or off state.
The circuitry of the video display device of the computer is capable of converting binary values
(0, 1) into a pixel on and pixel off information. 0 is represented by pixel off. 1 is represented
using pixel on. Using this ability graphics computer represent picture having discrete dots.
Any model of graphics can be reproduced with a dense matrix of dots or points. Most human
beings think graphics objects as points, lines, circles, ellipses. For generating graphical object,
many algorithms have been developed.
Pixel or Pel:
The term pixel is a short form of the picture element. It is also called a point or dot. It is the
smallest picture unit accepted by display devices. A picture is constructed from hundreds of such
pixels. Pixels are generated using commands. Lines, circle, arcs, characters; curves are drawn
with closely spaced pixels. To display the digit or letter matrix of pixels is used.
The closer the dots or pixels are, the better will be the quality of picture. Closer the dots are,
crisper will be the picture. Picture will not appear jagged and unclear if pixels are closely spaced.
So the quality of the picture is directly proportional to the density of pixels on the screen.
Pixels are also defined as the smallest addressable unit or element of the screen. Each pixel can
be assigned an address as shown in fig:
24
Different graphics objects can be generated by setting the different intensity of pixels and
different colors of pixels. Each pixel has some co-ordinate value. The coordinate is represented
using row and column.
P (5, 5) used to represent a pixel in the 5th row and the 5th column. Each pixel has some intensity
value which is represented in memory of computer called a frame buffer. Frame Buffer is also
called a refresh buffer. This memory is a storage area for storing pixels values using which
pictures are displayed. It is also called as digital memory. Inside the buffer, image is stored as a
pattern of binary digits either 0 or 1. So there is an array of 0 or 1 used to represent the picture. In
black and white monitors, black pixels are represented using 1's and white pixels are represented
using 0's. In case of systems having one bit per pixel frame buffer is called a bitmap. In systems
with multiple bits per pixel it is called a pixmap.
25
SCAN Conversion of Line:
• A line connects two points.
• It is a basic element in graphics.
• You’ll need two spots between which to draw a line to draw a line.
A line, or line segment, can be uniquely described by two points, according to geometry. We also
know from algebra that a line can be defined by a slope, commonly denoted by the letter m, and a
y-axis intercept, denoted by the letter b. A line in computer graphics is usually defined by two
endpoints. However, most line-drawing algorithms calculate the slope and y- intercept as
intermediate outputs.
Line Drawing algorithms:
Given the inherent restrictions of a raster display, the purpose of every line drawing method is to
produce the best feasible approximation of an ideal line. Before getting into specific line drawing
algorithms, it’s a good idea to think about the needs for such algorithms in general.
In this algorithm, we have two endpoints. We find the slope of the line by using both the points,
and we put the slope in the line equation y = mx + b.
Then we find the value of b by putting x and y equal to 0. After this, we have a relation between
x and y. Now we increase the value of x and find the corresponding value of y.
These values will be the intermediate points of the line. After finding the intermediate points
we’ll plot those points and draw the line.
26
It is the simplest form of conversion. First of all scan P1 and P2 points. P1 has co-ordinates
(x1',y1') and (x2' y2' ).
27
Algorithm for drawing line using equation:
Step1: Start Algorithm
Step2: Declare variables x1,x2,y1,y2,dx,dy,m,b,
Step3: Enter values of x1,x2,y1,y2.
The (x1,y1) are co-ordinates of a starting point of the line.
The (x2,y2) are co-ordinates of a ending point of the line.
Step4: Calculate dx = x2- x1
Step5: Calculate dy = y2-y1
Step6: Calculate m =
Step7: Calculate b = y1-m* x1
Step8: Set (x, y) equal to starting point, i.e., lowest point and xendequal to largest value of x.
If dx < 0
then x = x2
y = y2
xend= x1
If dx > 0
then x = x1
y = y1
xend= x2
Step9: Check whether the complete line has been drawn if x=xend, stop
Step10: Plot a point at current (x, y) coordinates
Step11: Increment value of x, i.e., x = x+1
Step12: Compute next value of y from equation y = mx + b.
Step13: Go to Step9.
Program to draw a line using LineSlope Method
#include <graphics.h>
#include <stdlib.h>
28
#include <math.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
class bresen
{
float x, y, x1, y1, x2, y2, dx, dy, m, c, xend;
public:
void get ();
void cal ();
};
void main ()
{
bresen b;
[Link] ();
[Link] ();
getch ();
}
Void bresen :: get ()
{
print ("Enter start & end points");
print ("enter x1, y1, x2, y2");
scanf ("%f%f%f%f",sx1, sx2, sx3, sx4)
}
void bresen ::cal ()
{
/* request auto detection */
int gdriver = DETECT,gmode, errorcode;
/* initialize graphics and local variables */
initgraph (&gdriver, &gmode, " ");
/* read result of initialization */
errorcode = graphresult ();
if (errorcode ! = grOK) /*an error occurred */
{
printf("Graphics error: %s \n", grapherrormsg (errorcode);
printf ("Press any key to halt:");
getch ();
exit (1); /* terminate with an error code */
}
dx = x2-x1;
dy=y2-2y1;
m = dy/dx;
c = y1 - (m * x1);
if (dx<0)
29
{
x=x2;
y=y2;
xend=x1;
}
else
{
x=x1;
y=y1;
xend=x2;
}
while (x<=xend)
{
putpixel (x, y, RED);
y++;
y=(x*x) +c;
}
}
OUTPUT:
Enter Starting and End Points
Enter (X1, Y1, X2, Y2) 200 100 300 200
The incremental technique is used in this algorithm. It means that we can find the next
coordinates by using past coordinates as a guide. In this method, the difference of pixel point is
analyzed and according to the analysis, the line can be drawn.
We’ll start with the initial position and work our way to the ending position by looking for
intermediate places. The slope of the line will be the ratio of difference of y-coordinates and the
difference of x-coordinates.
Δy = (y2 -y1), Δx = (x2 - x1)
30
where, (x1, y1) and (x2, y2) are the endpoints.
The Digital Differential Analyzer algorithm is based on the values of Δx and Δy.
Δy = m * Δx, Δx = Δy / m
The value of the slope will be either positive or negative. If the value of the slope is positive then
the values of Δx and Δy are increased otherwise their values are decreased.
(i). If (m < 1): xN = x1 + 1, yN = y1 + m
(ii). If (m > 1): xN = x1 + 1 / m, yN = y1 +1
(iii). If (m = 1): xN = x1 + 1, yN = y1 + 1
Advantage:
1. It is a faster method than method of using direct use of line equation.
2. This method does not use multiplication theorem.
3. It allows us to detect the change in the value of x and y, so plotting of same point twice is
not possible.
4. This method gives overflow indication when a point is repositioned.
5. It is an easy method because each step involves just two additions.
Disadvantage:
1. It involves floating point additions rounding off is done. Accumulations of round off error
cause accumulation of error.
2. Rounding off operations and floating-point operations consumes a lot of time.
3. It is more suitable for generating line using the software. But it is less suited for hardware
implementation.
DDA Algorithm:
Step1: Start Algorithm
Step2: Declare x1,y1,x2,y2,dx,dy,x,y as integer variables.
Step3: Enter value of x1,y1,x2,y2.
Step4: Calculate dx = x2-x1
Step5: Calculate dy = y2-y1
Step6: If ABS (dx) > ABS (dy)
Then step = abs (dx)
Else
Step7: xinc=dx/step
yinc=dy/step
31
assign x = x1
assign y = y1
Step8: Set pixel (x, y)
Step9: x = x + xinc
y = y + yinc
Set pixels (Round (x), Round (y))
Step10: Repeat step 9 until x = x2
Step11: End Algorithm
Example: If a line is drawn from (2, 3) to (6, 15) with use of DDA. How many points will
needed to generate such line?
Solution: P1 (2,3) P11 (6,15)
x1=2
y1=3
x2= 6
y2=15
dx = 6 - 2 = 4
dy = 15 - 3 = 12
m=
32
#include<stdio.h>
void main()
{
intgd = DETECT ,gm, i;
float x, y,dx,dy,steps;
int x0, x1, y0, y1;
initgraph(&gd, &gm, "C:\\TC\\BGI");
setbkcolor(WHITE);
x0 = 100 , y0 = 200, x1 = 500, y1 = 300;
dx = (float)(x1 - x0);
dy = (float)(y1 - y0);
if(dx>=dy)
{
steps = dx;
}
else
{
steps = dy;
}
dx = dx/steps;
dy = dy/steps;
x = x0;
y = y0;
i = 1;
while(i<= steps)
{
putpixel(x, y, RED);
x += dx;
y += dy;
i=i+1;
}
getch();
closegraph();
}
Output:
33
Method-3: Bresenham’s Line Generation:
Another incremental scan conversion procedure is the Bresenham’s algorithm. The big advantage
of this algorithm is that, it uses only integer calculations.
This method’s calculation is incredibly quick, which is why the line is drawn swiftly. We’ll need
the two endpoints in this and then we have to find the decision parameters.
Assume a pixel P1'(x1',y1'),then select subsequent pixels as we work our may to the night, one
pixel position at a time in the horizontal direction toward P2'(x2',y2').
Once a pixel in choose at any step
The next pixel is
1. Either the one to its right (lower-bound for the line)
2. One top its right and up (upper-bound for the line)
The line is best approximated by those pixels that fall the least distance from the path
between P1',P2'.
To chooses the next one between the bottom pixel S and top pixel T.
If S is chosen
We have xi+1=xi+1 and yi+1=yi
If T is chosen
We have xi+1=xi+1 and yi+1=yi+1
The actual y coordinates of the line at x = xi+1is
y=mxi+1+b
34
The distance from S to the actual line in y direction
s = y-yi
The distance from T to the actual line in y direction
t = (yi+1)-y
Now consider the difference between these 2 distance values
s-t
When (s-t) <0 ⟹ s < t
The closest pixel is S
When (s-t) ≥0 ⟹ s < t
The closest pixel is T
This difference is
s-t = (y-yi)-[(yi+1)-y]
= 2y - 2yi -1
di=△x (2 (xi+1)+2b-2yi-1)
=2△xyi-2△y-1△x.2b-2yi△x-△x
di=2△[Link]-2△[Link]+c
Where c= 2△y+△x (2b-1)
We can write the decision variable di+1 for the next slip on
di+1=2△[Link]+1-2△[Link]+1+c
di+1-di=2△y.(xi+1-xi)- 2△x(yi+1-yi)
Since x_(i+1)=xi+1,we have
di+1+di=2△y.(xi+1-xi)- 2△x(yi+1-yi)
Special Cases
If chosen pixel is at the top pixel T (i.e., di≥0)⟹ yi+1=yi+1
di+1=di+2△y-2△x
If chosen pixel is at the bottom pixel T (i.e., di<0)⟹ yi+1=yi
di+1=di+2△y
Finally, we calculate d1
d1=△x[2m(x1+1)+2b-2y1-1]
d1=△x[2(mx1+b-y1)+2m-1]
35
3. It can be implemented using hardware because it does not use multiplication and
division.
4. It is faster as compared to DDA (Digital Differential Analyzer) because it does not
involve floating point calculations like DDA Algorithm.
Disadvantage:
1. This algorithm is meant for basic line drawing only Initializing is not a part of
Bresenham's line algorithm. So to draw smooth lines, you should want to look into a
different algorithm.
Bresenham's Line Algorithm:
Step1: Start Algorithm
Step2: Declare variable x1,x2,y1,y2,d,i1,i2,dx,dy
Step3: Enter value of x1,y1,x2,y2
Where x1,y1are coordinates of starting point
And x2,y2 are coordinates of Ending point
Step4: Calculate dx = x2-x1
Calculate dy = y2-y1
Calculate i1=2*dy
Calculate i2=2*(dy-dx)
Calculate d=i1-dx
Step5: Consider (x, y) as starting point and xendas maximum possible value of x.
If dx < 0
Then x = x2
y = y2
xend=x1
If dx > 0
Then x = x1
y = y1
xend=x2
Step6: Generate point at (x,y)coordinates.
Step7: Check if whole line is generated.
If x > = xend
Stop.
Step8: Calculate co-ordinates of the next pixel
If d < 0
Then d = d + i1
If d ≥ 0
Then d = d + i2
Increment y = y + 1
Step9: Increment x = x + 1
Step10: Draw a point of latest (x, y) coordinates
Step11: Go to step 7
Step12: End of Algorithm
36
Example: Starting and Ending position of the line are (1, 1) and (8, 5).
Find intermediate points.
Solution: x1=1
y1=1
x2=8
y2=5
dx= x2-x1=8-1=7
dy=y2-y1=5-1=4
I1=2* ∆y=2*4=8
I2=2*(∆y-∆x)=2*(4-7)=-6
d = I1-∆x=8-7=1
x y d=d+I1 or I2
1 1 d+I2=1+(-6)=-5
2 2 d+I1=-5+8=3
3 2 d+I2=3+(-6)=-3
4 3 d+I1=-3+8=5
5 3 d+I2=5+(-6)=-1
6 4 d+I1=-1+8=7
7 4 d+I2=7+(-6)=1
8 5
37
Program to implement Bresenham's Line Drawing Algorithm:
#include<stdio.h>
#include<graphics.h>
void drawline(int x0, int y0, int x1, int y1)
{
int dx, dy, p, x, y;
dx=x1-x0;
dy=y1-y0;
x=x0;
y=y0;
p=2*dy-dx;
while(x<x1)
{
if(p>=0)
{
putpixel(x,y,7);
y=y+1;
p=p+2*dy-2*dx;
}
else
{
putpixel(x,y,7);
p=p+2*dy;}
x=x+1;
}
}
int main()
{
int gdriver=DETECT, gmode, error, x0, y0, x1, y1;
initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");
printf("Enter co-ordinates of first point: ");
scanf("%d%d", &x0, &y0);
printf("Enter co-ordinates of second point: ");
scanf("%d%d", &x1, &y1);
drawline(x0, y0, x1, y1);
38
return 0;
}
Output:
1 DDA Algorithm use floating point, i.e., Real Bresenham's Line Algorithm use fixed point,
Arithmetic. i.e., Integer Arithmetic
2 DDA Algorithms uses multiplication & Bresenham's Line Algorithm uses only
division its operation subtraction and addition its operation
3 DDA Algorithm is slowly than Bresenham's Bresenham's Algorithm is faster than DDA
Line Algorithm in line drawing because it Algorithm in line because it involves only
uses real arithmetic (Floating Point addition & subtraction in its calculation and
operation) uses only integer arithmetic.
4 DDA Algorithm is not accurate and efficient Bresenham's Line Algorithm is more accurate
as Bresenham's Line Algorithm. and efficient at DDA Algorithm.
5 DDA Algorithm can draw circle and curves Bresenham's Line Algorithm can draw circle
but are not accurate as Bresenham's Line and curves with more accurate than DDA
Algorithm Algorithm.
39
Bresenham's Circle Algorithm:
Scan-Converting a circle using Bresenham's algorithm works as follows: Points are generated
from 90° to 45°, moves will be made only in the +x & -y directions as shown in fig:
The best approximation of the true circle will be described by those pixels in the raster
that falls the least distance from the true circle. We want to generate the points from 90°
to 45°. Assume that the last scan-converted pixel is P1 as shown in fig.
Each new point closest to the true circle can be found by taking either of two actions.
1. Move in the x-direction one unit or
2. Move in the x- direction one unit & move in the negative y-direction one unit.
Let D (Si) is the distance from the origin to the true circle squared minus the distance to
point P3 squared. D (Ti) is the distance from the origin to the true circle squared minus the
distance to point P2 squared. Therefore, the following expressions arise.
D (Si)=(xi-1+1)2+ yi-12 -r2
D (Ti)=(xi-1+1)2+(yi-1 -1)2-r2
Since D (Si) will always be +ve & D (Ti) will always be -ve, a decision variable d may be
defined as follows:
40
di=D (Si )+ D (Ti)
Therefore,
di=(xi-1+1)2+ yi-12 -r2+(xi-1+1)2+(yi-1 -1)2-r2
From this equation, we can drive initial values of di as
If it is assumed that the circle is centered at the origin, then at the first step x = 0 & y = r.
Therefore,
di=(0+1)2+r2 -r2+(0+1)2+(r-1)2-r2
=1+1+r2-2r+1-r2
= 3 - 2r
41
putpixel (-y+p, -x+q)
putpixel (y+p, -x+q)
putpixel (x+p, -y-q)
Step8: Find location of next pixels to be scanned
If d < 0
then d = d + 4x + 6
increment x = x + 1
If d ≥ 0
then d = d + 4 (x - y) + 10
increment x = x + 1
decrement y = y - 1
Step9: Go to step 6
Step10: Stop Algorithm
42
So P1 (0,0)⟹(50,50)
P2 (1,10)⟹(51,60)
P3 (2,10)⟹(52,60)
P4 (3,9)⟹(53,59)
P5 (4,9)⟹(54,59)
P6 (5,8)⟹(55,58)
Program to draw a circle using Bresenham's circle drawing algorithm:
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
while(x<=y)
{
if(d<=0)
{
d=d+(4*x)+6;
}
else
{
d=d+(4*x)-(4*y)+10;
y=y-1;
}
x=x+1;
EightWaySymmetricPlot(xc,yc,x,y);
}
}
int main(void)
{
/* request auto detection */
int xc,yc,r,gdriver = DETECT, gmode, errorcode;
/* initialize graphics and local variables */
43
initgraph(&gdriver, &gmode, "C:\\TURBOC3\\BGI");
getch();
closegraph();
return 0;
}
Output:
44
MidPoint Circle Algorithm
It is based on the following function for testing the spatial relationship between the arbitrary
point (x, y) and a circle of radius r centered at the origin:
Now, consider the coordinates of the point halfway between pixel T and pixel S
If Pi is+ve ⟹midpoint is outside the circle (or on the circle)and we choose pixel S.
45
We can continue to simplify this in n terms of (xi,yi) and get
We can put ≅1
∴r is an integer
So, P1=1-r
Algorithm:
Step1: Put x =0, y =r in equation 2
We have p=1-r
Step2: Repeat steps while x ≤ y
Plot (x, y)
If (p<0)
Then set p = p + 2x + 3
Else
p = p + 2(x-y)+5
y =y - 1 (end if)
x =x+1 (end loop)
Step3: End
class bresen
{
float x, y,a, b, r, p;
public:
void get ();
void cal ();
};
void main ()
{
bresen b;
[Link] ();
46
[Link] ();
getch ();
}
Void bresen :: get ()
{
cout<<"ENTER CENTER AND RADIUS";
cout<< "ENTER (a, b)";
cin>>a>>b;
cout<<"ENTER r";
cin>>r;
}
void bresen ::cal ()
{
/* request auto detection */
int gdriver = DETECT,gmode, errorcode;
int midx, midy, i;
/* initialize graphics and local variables */
initgraph (&gdriver, &gmode, " ");
/* read result of initialization */
errorcode = graphresult ();
if (errorcode ! = grOK) /*an error occurred */
{
printf("Graphics error: %s \n", grapherrormsg (errorcode);
printf ("Press any key to halt:");
getch ();
exit (1); /* terminate with an error code */
}
x=0;
y=r;
putpixel (a, b+r, RED);
putpixel (a, b-r, RED);
putpixel (a-r, b, RED);
putpixel (a+r, b, RED);
p=5/4)-r;
while (x<=y)
{
If (p<0)
p+= (4*x)+6;
else
{
p+=(2*(x-y))+5;
y--;
}
x++;
putpixel (a+x, b+y, RED);
putpixel (a-x, b+y, RED);
putpixel (a+x, b-y, RED);
putpixel (a+x, b-y, RED);
putpixel (a+x, b+y, RED);
putpixel (a+x, b-y, RED);
putpixel (a-x, b+y, RED);
putpixel (a-x, b-y, RED);
47
}
}
Output:
48
printf("Enter the value of yc\t");
scanf("%d",&yc);
printf("Enter X axis length\t");
scanf("%d",&a);
printf("Enter Y axis length\t");
scanf("%d",&b);
x=0;y=b;
disp();
p1=(b*b)-(a*a*b)+(a*a)/4;
while((2.0*b*b*x)<=(2.0*a*a*y))
{
x++;
if(p1<=0)
p1=p1+(2.0*b*b*x)+(b*b);
else
{
y--;
p1=p1+(2.0*b*b*x)+(b*b)-(2.0*a*a*y);
}
disp();
x=-x;
disp();
x=-x;
delay(50);
}
x=a;
y=0;
disp();
p2=(a*a)+2.0*(b*b*a)+(b*b)/4;
while((2.0*b*b*x)>(2.0*a*a*y))
{
y++;
if(p2>0)
p2=p2+(a*a)-(2.0*a*a*y);
else
{
x--;
p2=p2+(2.0*b*b*x)-(2.0*a*a*y)+(a*a);
}
disp();
y=-y;
disp();
y=-y;
delay(50);
}
getch();
closegraph();
}
void disp()
{
putpixel(xc+x,yc+y,7);
putpixel(xc-x,yc+y,7);
49
putpixel(xc+x,yc-y,7);
putpixel(xc+x,yc-y,7);
}
Output:
1. Polynomial Method:
The ellipse has a major and minor axis. If a1 and b1are major and minor axis respectively. The
centre of ellipse is (i, j). The value of x will be incremented from i to a1and value of y will be
calculated using the following formula
50
Algorithm:
1. Set the initial variables: a = length of major axis; b = length of minor axis; (h, k) = coordinates
of ellipse center; x = 0; i = step; xend = a.
2. Test to determine whether the entire ellipse has been scan-converted. If x>xend, stop.
3. Compute the value of the y coordinate:
4. Plot the four points, found by symmetry, at the current (x, y) coordinates:
Plot (x + h, y + k) Plot (-x + h, -y + k) Plot (-y - h, x + k) Plot (y + h, -x
+ k)
5. Increment x; x = x + i.
6. Go to step 2.
Program to draw an Ellipse using Polynomial Method:
#include <graphics.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
class bresen
{
float x, y, a, b, r, t, te, xend, h, k, step;
public:
void get ();
void cal ();
};
void main ()
{
bresen b;
[Link] ();
[Link] ();
getch ();
}
void bresen :: get ()
{
cout<<"\n ENTER CENTER OF ELLIPSE";
cout<<"\n enter (h, k) ";
cin>>h>>k;
cout<<"\n ENTER LENGTH OF MAJOR AND MINOR AXIS";
cin>>a>>b;
cout<<"\n ENTER Step Size";
cin>> step;
}
void bresen ::cal ()
{
/* request auto detection */
int gdriver = DETECT,gmode, errorcode;
int midx, midy, i;
/* initialize graphics and local variables */
51
initgraph (&gdriver, &gmode, " ");
/* read result of initialization */
errorcode = graphresult ();
if (errorcode ! = grOK) /*an error occurred */
{
printf("Graphics error: %s \n", grapherrormsg (errorcode);
printf ("Press any key to halt:");
getch ();
exit (1); /* terminate with an error code */
}
x = 0;
xend=a;
whilex (x<xend)
{
t= (1-((x * x)/ (a * a)));
if (t<0)
te=-t;
else
te=t;
y=b * sqrt (te);
putpixel (h+x, k+y, RED);
putpixel (h-x, k+y, RED);
putpixel (h+x, y-y, RED);
putpixel (h-x, k-y, RED);
x+=step;
}
getch();
}
Output:
2. Trignometric Method:
The following equation defines an ellipse trigonometrically as shown in fig:
x = a * cos (θ) +h and
y = b * sin (θ)+k
where (x, y) = the current coordinates
a = length of major axis
52
b = length of minor axis
θ= current angle
(h, k) = ellipse center
In this method, the value of θ is varied from 0 to radians. The remaining points are found by
symmetry.
Drawback:
1. This is an inefficient method.
2. It is not an interactive method for generating ellipse.
3. The table is required to see the trigonometric value.
4. Memory is required to store the value of θ.
Algorithm:
Step1: Start Algorithm
Step2: Declare variable x1,y1,aa1,bb1,aa2,bb2,fx,fy,p1,a1,b1
Step3: Initialize x1=0 and y1=b/* values of starting point of circle */
Step4: Calculate aa1=a1*a1
Calculate bb1=b1* b1
Calculate aa2=aa1*2
Calculate bb2=bb1*2
Step5: Initialize fx = 0
Step6: Initialize fy = aa_2* b1
Step7: Calculate the value of p1and round if it is integer
p1=bb1-aa1* b1+0.25* aa1/
Step8:
While (fx < fy)
{
Set pixel (x1,y1)
Increment x i.e., x = x + 1
Calculate fx = fx + bb2
If (p1 < 0)
Calculate p1 = p1 + fx + bb1/
53
else
{
Decrement y i.e., y = y-1
Calculate fy = fy - 992;
p1=p1 + fx + bb1-fy
}
}
Step9: Setpixel (x1,y1)
Step10: Calculate p1=bb1 (x+.5)(x+.5)+aa(y-1)(y-1)-aa1*bb1
Step 11:
While (y1>0)
{
Decrement y i.e., y = y-1
fy=fx-aa2/
if (p1>=0)
p1=p1 - fx + aa1/
else
{
Increment x i.e., x = x + 1
fx= fx+bb_2
p1=p1+fx-fy-aa1
}
}
Set pixel (x1,y1)
Step12: Stop Algorithm
Program to draw a circle using Trigonometric method:
#include <graphics.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
# define pi 3.14
class bresen
{
float a, b, h, k, thetaend,step,x,y;
int i;
public:
void get ();
void cal ();
};
void main ()
{
bresen b;
[Link] ();
[Link] ();
getch ();
54
}
void bresen :: get ()
{
cout<<"\n ENTER CENTER OF ELLIPSE";
cin>>h>>k;
cout<<"\n ENTER LENGTH OF MAJOR AND MINOR AXIS";
cin>>a>>b;
cout<<"\n ENTER STEP SIZE";
cin>> step;
}
void bresen ::cal ()
{
/* request auto detection */
int gdriver = DETECT,gmode, errorcode;
int midx, midy, i;
/* initialize graphics and local variables */
initgraph (&gdriver, &gmode, " ");
/* read result of initialization */
errorcode = graphresult ();
if (errorcode ! = grOK) /*an error occurred */
{
printf("Graphics error: %s \n", grapherrormsg (errorcode);
printf ("Press any key to halt:");
getch ();
exit (1); /* terminate with an error code */
}
theta= 0;
thetaend=(pi*90)/180;
whilex (theta<thetaend)
{
x = a * cos (theta);
y = b * sin (theta);
putpixel (x+h, y+k, RED);
putpixel (-x+h, y+k, RED);
putpixel (-x+h, -y+k, RED);
putpixel (x+h, -y+k, RED);
theta+=step;
}
getch();
}
Output:
55
Ellipse Axis Rotation:
Since the ellipse shows four-way symmetry, it can easily be rotated. The new equation is found
by trading a and b, the values which describe the major and minor axes. When the polynomial
method is used, the equations used to describe the ellipse become
56
Now divide the elliptical curve from (0, b) to (a, 0) into two parts at point Q where the slope of
the curve is -1.
Slope of the curve is defined by the f(x, y) = 0 is where fx & fy are partial derivatives
of f(x, y) with respect to x & y.
We have fx = 2b2 x, fy=2a2 y & Hence we can monitor the slope value during the
scan conversion process to detect Q. Our starting point is (0, b)
Suppose that the coordinates of the last scan converted pixel upon entering step i are (xi,yi). We
are to select either T (xi+1),yi) or S (xi+1,yi-1) to be the next pixel. The midpoint of T & S is used to
define the following decision parameter.
pi = f(xi+1),yi- )
pi+1=f(xi+1+1,yi+1- )
57
pi+1in terms of pi and (xi+1,yi+1): pi+1= pi+2b2 xi+1+b2 if pi<0 =
2 2 2
pi+2b xi+1+b -2a yi+1 if pi>0
The initial value for the recursive expression can be obtained by the evaluating the original
definition of pi with (0, b):
qj=f(xj+ ,yj-1)
qj+1=f(xj+1+ ,yj+1-1)
58
}
}
Setpixel (x, y);
p=b2(x+0.5)2+ a2 (y-1)2- a2 b2
while (y>0)
{
y--;
fy=fy-2a2;
if (p>=0)
p=p-fy+a2
else
{
x++;
fx=fx+2b2
p=p+fx-fy+a2;
}
Setpixel (x,y);
}
Program to draw an ellipse using Midpoint Ellipse Algorithm:
#include <graphics.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
class bresen
{
float x,y,a, b,r,p,h,k,p1,p2;
public:
void get ();
void cal ();
};
void main ()
{
bresen b;
[Link] ();
[Link] ();
getch ();
}
void bresen :: get ()
{
cout<<"\n ENTER CENTER OF ELLIPSE";
cout<<"\n ENTER (h, k) ";
cin>>h>>k;
cout<<"\n ENTER LENGTH OF MAJOR AND MINOR AXIS";
cin>>a>>b;
}
void bresen ::cal ()
59
{
/* request auto detection */
int gdriver = DETECT,gmode, errorcode;
int midx, midy, i;
/* initialize graphics and local variables */
initgraph (&gdriver, &gmode, " ");
/* read result of initialization */
errorcode = graphresult ();
if (errorcode ! = grOK) /*an error occurred */
{
printf("Graphics error: %s \n", grapherrormsg (errorcode);
printf ("Press any key to halt:");
getch ();
exit (1); /* terminate with an error code */
}
x=0;
y=b;
// REGION 1
p1 =(b * b)-(a * a * b) + (a * a)/4);
{
putpixel (x+h, y+k, RED);
putpixel (-x+h, -y+k, RED);
putpixel (x+h, -y+k, RED);
putpixel (-x+h, y+k, RED);
if (p1 < 0)
p1 += ((2 *b * b) *(x+1))-((2 * a * a)*(y-1)) + (b * b);
else
{
p1+= ((2 *b * b) *(x+1))-((2 * a * a)*(y-1))-(b * b);
y--;
}
x++;
}
//REGION 2
p2 =((b * b)* (x + 0.5))+((a * a)*(y-1) * (y-1))-(a * a *b * b);
while (y>=0)
{
If (p2>0)
p2=p2-((2 * a * a)* (y-1))+(a *a);
else
{
p2=p2-((2 * a * a)* (y-1))+((2 * b * b)*(x+1))+(a * a);
x++;
}
y--;
putpixel (x+h, y+k, RED);
putpixel (-x+h, -y+k, RED);
putpixel (x+h, -y+k, RED);
putpixel (-x+h, y+k, RED);
}
getch();
}
60
OR
Midpoint ellipse drawing algorithm
Mid-point Ellipse algorithm is used to draw an ellipse in computer graphics.
Midpoint ellipse algorithm plots(finds) points of an ellipse on the first quadrant by dividing the
quadrant into two regions.
Each point(x, y) is then projected into other three quadrants (-x, y), (x, -y), (-x, -y) i.e. it uses 4-
way symmetry.
Function of ellipse:
fellipse(x, y)=ry2x2+rx2y2-rx2ry2
fellipse(x, y)<0 then (x, y) is inside the ellipse.
fellipse(x, y)>0 then (x, y) is outside the ellipse.
fellipse(x, y)=0 then (x, y) is on the ellipse.
Decision parameter:
Initially, we have two decision parameters p10 in region 1
and p20 in region 2.
These parameters are defined as : p10 in region 1 is given as :
p10=ry2+1/4rx2-rx2ry
61
9. Repeat the steps for region 1 until 2ry2x>=2rx2y
#include <stdio.h>
// For region 1
while (dx < dy) {
62
// printing points based on 4-way symmetry
printf("(%f, %f)\n", x + xc, y + yc);
printf("(%f, %f)\n", -x + xc, y + yc);
printf("(%f, %f)\n", x + xc, -y + yc);
printf("(%f, %f)\n", -x + xc, -y + yc);
// Driver code
int main()
{
// To draw a ellipse of major and
// minor radius 15, 10 centered at (50, 50)
midptellipse(10, 15, 50, 50);
return 0;
}
63
Unit:3 2D Geometric Transformation
Introduction of Transformations
In computer graphics, transformations refer to the operations that manipulate objects or images to
change their position, orientation, or size in a coordinate system. These transformations are
fundamental to rendering and modeling in graphics, and they help in the representation and
manipulation of 2D and 3D objects.
Transformations can be categorized into two types:
1. 2D Transformations (for two-dimensional objects)
2. 3D Transformations (for three-dimensional objects)
2D Transformation in Computer Graphics
In computer graphics, 2D transformations refer to operations that modify the position,
orientation, and size of objects in a two-dimensional space. These transformations are
represented by mathematical operations, typically using matrices. Below are the primary types of
2D transformations:
1. Translation
2. Scaling
3. Rotating
4. Reflection
5. Shearing
Homogenous Coordinates
To perform a sequence of transformation such as translation followed by rotation and scaling, we
need to follow a sequential process −
• Translate the coordinates,
• Rotate the translated coordinates, and then
• Scale the rotated coordinates to complete the composite transformation.
To shorten this process, we have to use 3×3 transformation matrix instead of 2×2 transformation
matrix. To convert a 2×2 matrix to 3×3 matrix, we have to add an extra dummy coordinate W.
In this way, we can represent the point by 3 numbers instead of 2 numbers, which is
called Homogenous Coordinate system. In this system, we can represent all the transformation
equations in matrix multiplication. Any Cartesian point P(X, Y) can be converted to homogenous
coordinates by P’ (Xh, Yh, h).
1. Translation
A translation moves an object to a different position on the screen. You can translate a point
in 2D by adding translation coordinate (tx, ty) to the original coordinate (X, Y) to get the new
coordinate (X’, Y’).
64
From the above figure, you can write that −
X’ = X + tx
Y’ = Y + ty
The pair (tx, ty) is called the translation vector or shift vector. The above equations can also be
represented using the column vectors.
We can write it as −
P’ = P + T
65
// function to translate line
void translateLine(int P[][2], int T[]) {
/* init graph and line() are used for
representing line through graphical
functions
*/
int gd = DETECT, gm, errorcode;
initgraph(&gd, &gm, "c:\\tc\\bgi");
// driver program
int main() {
int P[2][2] = {{5, 8}, {12, 18}}; // coordinates of points
int T[] = {2, 1}; // translation factor
translateLine(P, T);
return 0;
}
// Original rectangle
66
setcolor(2);
rectangle(P[0][0], P[0][1], P[1][0], P[1][1]);
// Translated rectangle
setcolor(3);
rectangle(P[0][0], P[0][1], P[1][0], P[1][1]);
delay(5000); // Delay to show the result
closegraph(); // Close graphics
}
// Driver program
int main()
{
// Rectangle coordinates of top left and bottom right
// points
int P[2][2] = { { 5, 8 }, { 12, 18 } };
int T[] = { 2, 1 }; // Translation factor
translateRectangle(P, T);
return 0;
}
2. Rotation
o In rotation, we rotate the object at particular angle θ (theta) from its origin. From the
following figure, we can see that the point P(X, Y) is located at angle φ from the horizontal X
coordinate with distance r from the origin.
o Let us suppose you want to rotate it at the angle θ. After rotating it to a new location, you will
get a new point P’ (X’, Y’).
Using standard trigonometric the original coordinate of point P(X, Y) can be represented as –
67
Same way we can represent the point P’ (X’, Y’) as –
Substituting equation (1) & (2) in (3) & (4) respectively, we will get
void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3);
void RotateTriangle(int x1, int y1, int x2, int y2, int x3, int y3, float angle);
int main()
{
68
int gd = DETECT, gm;
int x1, y1, x2, y2, x3, y3;
float angle;
printf("Enter the 1st point for the triangle (x1 y1): ");
scanf("%d%d", &x1, &y1);
printf("Enter the 2nd point for the triangle (x2 y2): ");
scanf("%d%d", &x2, &y2);
printf("Enter the 3rd point for the triangle (x3 y3): ");
scanf("%d%d", &x3, &y3);
getch();
closegraph();
return 0;
}
void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
line(x1, y1, x2, y2);
line(x2, y2, x3, y3);
line(x3, y3, x1, y1);
}
void RotateTriangle(int x1, int y1, int x2, int y2, int x3, int y3, float angle)
{
int p = x2, q = y2;
float radianAngle = (angle * 3.14) / 180.0;
69
int a3 = p + (x3 - p) * cos(radianAngle) - (y3 - q) * sin(radianAngle);
int b3 = q + (x3 - p) * sin(radianAngle) + (y3 - q) * cos(radianAngle);
setcolor(1);
DrawTriangle(a1, b1, a2, b2, a3, b3);
}
3. Scaling
To change the size of an object, scaling transformation is used. In the scaling process, you either
expand or compress the dimensions of the object. Scaling can be achieved by multiplying the
original coordinates of the object with the scaling factor to get the desired result.
Let us assume that the original coordinates are (X, Y), the scaling factors are (SX, SY), and the
produced coordinates are (X’, Y’). This can be mathematically represented as shown below –
The scaling factor SX, SY scales the object in X and Y direction respectively. The above
equations can also be represented in matrix form as below –
Where S is the scaling matrix. The scaling process is shown in the following figure.
If we provide values less than 1 to the scaling factor S, then we can reduce the size of the object.
If we provide values greater than 1, then we can increase the size of the object.
void draw();
void scale();
void main()
{
int gd = DETECT, gm;
int c;
initgraph(&gd, &gm, " ");
draw();
scale();
}
void draw()
{
line(x1, y1, x2, y2);
line(x2, y2, x3, y3);
line(x3, y3, x1, y1);
}
void scale()
{
int x, y;
int mx, my;
mx = (x1 + x2 + x3) / 3;
my = (y1 + y2 + y3) / 3;
71
cleardevice();
draw();
getch();
}
4. Reflection
Reflection is the mirror image of original object. In other words, we can say that it is a rotation
operation with 180°. In reflection transformation, the size of the object does not change. The
following figures show reflections with respect to X and Y axes, and about the origin
respectively.
Types of Reflection:
1. Reflection about the x-axis
2. Reflection about the y-axis
3. Reflection about an axis perpendicular to xy plane and passing through the origin
4. Reflection about line y=x
1. Reflection about x-axis: The object can be reflected about x-axis with the help of the
following matrix
In this transformation value of x will remain same whereas the value of y will become negative.
Following figures shows the reflection of the object axis. The object will lie another side of the x-
axis.
72
[Link] about y-axis: The object can be reflected about y-axis with the help of following
transformation matrix
Here the values of x will be reversed, whereas the value of y will remain the same. The object
will lie another side of the y-axis.
The following figure shows the reflection about the y-axis
73
In this value of x and y both will be reversed. This is also called as half revolution about the
origin.
4. Reflection about line y=x: The object may be reflected about line y = x with the help of
following transformation matrix
First of all, the object is rotated at 45°. The direction of rotation is clockwise. After it reflection is
done concerning x-axis. The last step is the rotation of y=x back to its original position that is
counterclockwise at 45°.
74
Solution:
75