0% found this document useful (0 votes)
3 views75 pages

Computer Graphics

The document provides an overview of computer graphics, including its definition, types (raster and vector graphics), and various applications across fields such as education, entertainment, and design. It also discusses popular software used in computer graphics, input/output devices, and the differences between interactive and passive graphics. Additionally, it covers display technologies and the components of Cathode Ray Tube (CRT) displays, highlighting the evolution and future of display technology.

Uploaded by

gaikwaddeepali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views75 pages

Computer Graphics

The document provides an overview of computer graphics, including its definition, types (raster and vector graphics), and various applications across fields such as education, entertainment, and design. It also discusses popular software used in computer graphics, input/output devices, and the differences between interactive and passive graphics. Additionally, it covers display technologies and the components of Cathode Ray Tube (CRT) displays, highlighting the evolution and future of display technology.

Uploaded by

gaikwaddeepali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to 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.

Computer Graphics refers to several things


• The manipulation and the representation of the image or the data in a graphical manner.
• Various technologies are required for the creation and manipulation.
• Digital synthesis and its manipulation.
Computer graphics is a wide-ranging topic that covers rendering, modeling, and visualization
techniques.

Types of Computer Graphics


• Raster Graphics: In raster, graphics pixels are used for an image to be drawn. It is also
known as a bitmap image in which a sequence of images is into smaller pixels. Basically, a
bitmap indicates a large number of pixels together.
• Vector Graphics: In vector graphics, mathematical formulae are used to draw different
types of shapes, lines, objects, and so on.

Applications of Computer Graphics


There are many applications of computer graphics discussed below-
1. Computer Graphics are used for the aided design of systems engineering and
architectural systems- These are used in electrical automobiles and electro-
mechanical, and electronic devices. For example gears and bolts.
2. Computer Art – Computer Graphics are also used in the field of commercial arts. It is
used to generate television and advertising commercial. For example- MS Paint.
3. Presentation Graphics – It is used to summarize financial statistical scientific or
economic data. For example- Bar charts systems and line charts.
4. Entertainment- Computer Graphics are now commonly used in making motion pictures,
music videos and television shows.
5. Education and training- Computer-generated model of the physical, financial and
economic system is often used as educational aids. Model of physical systems,
physiological system, population trends or equipment can help trainees to understand
the operation of the system. For example Flight Simulator.
Flight Simulator: It helps in giving training to the pilots of airplanes. These pilots
spend much of their training not in a real aircraft but on the ground at the controls of a
Flight Simulator.
Advantages: Fuel Saving, Safety, Ability to familiarize the training with a large
number of the world's airports.
6. Visualization- To study trends and patterns. For example- Analyzing satellite photos of
earth.
7. Use in Biology- Molecular biologist can display a picture of molecules and gain insight
into their structure with the help of computer graphics.
8. Computer-Generated Maps: Town planners and transportation engineers can use
computer-generated maps which display data useful to them in their planning work.
9. Architect: Architect can explore an alternative solution to design problems at an
interactive graphics terminal. In this way, they can test many more solutions that would
not be possible without the computer.

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.

Popular Computer Graphics Software


1. 2D Graphics Software
Adobe Photoshop: For image editing and graphic design.
CorelDRAW: Vector graphics and illustration software.
GIMP: Open-source alternative for image manipulation.
2. 3D Modeling and Animation Software
Autodesk Maya: Industry standard for 3D modeling and animation.
Blender: Open-source tool for 3D modeling, animation, and rendering.
3ds Max: Often used in games, movies, and architectural visualization.
3. Rendering Software
V-Ray: Advanced rendering for realistic visuals.
Arnold: Rendering tool used in animation and VFX production.
4. Game Engines
Unity: Popular engine for 2D/3D game development and real-time applications.
Unreal Engine: Known for high-quality rendering in games and virtual production.
5. Simulation Software
Houdini: Procedural modeling and simulation, especially for effects like smoke and fire.
ANSYS: Used in engineering simulations for physical systems.
6. CAD and Engineering Software
AutoCAD: Widely used in engineering and architectural design.
SolidWorks: Mechanical design and engineering software.
7. Virtual Reality (VR) and Augmented Reality (AR) Software
Unity and Unreal Engine: Support VR/AR content development.
Tilt Brush: A VR painting application.
8. Scientific Visualization Tools
ParaView: Open-source tool for large data visualization.
MATLAB: Includes plotting and 3D visualization tools.

Description of some Graphics Devices


Input and Output Devices
An input/output device, often known as an IO device, is any hardware that allows a human
operator or other systems to interface with a computer. Input/output devices, as the name
implies, are capable of delivering data (output) to and receiving data from a computer (input).

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.

These Devices include:

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:

1. Trackball is stationary, so it does not require much space


to use it.
2. Compact Size

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:

1. It is used for three-dimensional positioning of the object.


2. It is used to select various functions in the field of virtual reality.
3. It is applicable in CAD applications.
4. Animation is also done using spaceball.
5. It is used in the area of simulation and modeling.

4
5. Joystick:

A Joystick is also a pointing device which is used to change


cursor position on a monitor screen. Joystick is a stick having a
spherical ball as its both lower and upper ends as shown in fig.
The lower spherical ball moves in a socket. The joystick can be
changed in all four directions. The function of a joystick is
similar to that of the mouse. It is mainly used in Computer
Aided Designing (CAD) and playing computer games.

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:

1. Light Pens can be used as input coordinate positions by providing necessary


arrangements.
2. If background color or intensity, a light pen can be used as a
locator.
3. It is used as a standard pick device with many graphics system.
4. It can be used as stroke input devices.
5. It can be used as valuators.

Interactive and Passive Graphics


(a) Non-Interactive or Passive Computer Graphics:

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.

(b) Interactive Computer Graphics:

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.

Working of Interactive Computer Graphics:


The modern graphics display is very simple in construction. It consists of three components:

1. Frame Buffer or Digital Memory


2. A Monitor likes a home T.V. set without the tuning and receiving electronics.
3. Display Controller or Video Controller: It passes the contents of the frame buffer to the

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.

Properties of Video Monitor:


1. Persistence: Persistence is the duration of phosphorescence. Different kinds of phosphors are
available for use in CRT. Besides color, a major difference between phosphor in their persistence
how they continue to emit light after the electron beam is removed.
2. Resolution: Use to describe the number of pixels that are used on display image.
3. Aspect Ratio: It is the ratio of width to its height. Its measure is unit in length or number of
pixels.
width unit
Aspect Ratio =height unit

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.

Cathode Ray Tube (CRT): Storage Tube Graphic Display


CRT stands for Cathode Ray Tube. CRT is a technology used in traditional computer monitors
and televisions. The image on CRT display is created by firing electrons from the back of the
tube of phosphorus located towards the front of the screen.

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.

Raster Scan Display:


A Raster Scan Display is based on intensity control of pixels in the form of a rectangular box
called Raster on the screen. Information of on and off pixels is stored in refresh buffer or Frame
buffer. Televisions in our house are based on Raster Scan Method. The raster scan system can
store information of each pixel position, so it is suitable for realistic display of objects. Raster
Scan provides a refresh rate of 60 to 80 frames per second.

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

Differentiate between Random and Raster Scan Display:

Random Scan Raster Scan


1. It has high Resolution 1. Its resolution is low.
2. It is more expensive 2. It is less expensive
3. Any modification if needed is easy [Link] is tough
4. Solid pattern is tough to fill [Link] pattern is easy to fill
5. Refresh rate depends or resolution 5. Refresh rate does not depend on the
picture.
6. Only screen with view on an area is 6. Whole screen is scanned.
displayed.
7. Beam Penetration technology come under 7. Shadow mark technology came under this.
it.
8. It does not use interlacing method. 8. It uses interlacing
9. It is restricted to line drawing applications 9. It is suitable for realistic display.
Color CRT Monitors:
The CRT Monitor display by using a combination of phosphors. The phosphors are different
colors. There are two popular approaches for producing color displays with a CRT are:

1. Beam Penetration Method


2. Shadow-Mask Method

1. Beam Penetration Method:


The Beam-Penetration method has been used with random-scan monitors. In this method, the
CRT screen is coated with two layers of phosphor, red and green and the displayed color depends
on how far the electron beam penetrates the phosphor layers. This method produces four colors
only, red, green, orange and yellow. A beam of slow electrons excites the outer red layer only;
hence screen shows red color only. A beam of high-speed electrons excites the inner green layer.
Thus screen shows a green color.

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.

o One phosphor dot emits: red light


o Another emits: green light
o Third emits: blue light
This type of CRT has 3 electron guns, one for each color dot and a shadow mask grid just behind
the phosphor coated screen.
Shadow mask grid is pierced with small round holes in a triangular pattern.
Figure shows the delta-delta shadow mask method commonly used in color CRT system.

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

Direct View Storage Tubes:


DVST terminals also use the random scan approach to generate the image on the CRT screen.
The term "storage tube" refers to the ability of the screen to retain the image which has been
projected against it, thus avoiding the need to rewrite the image constantly.

Function of guns: Two guns are used in DVST

1. Primary guns: It is used to store the picture pattern.


2. Flood gun or Secondary gun: It is used to maintain picture display.

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.

Flat Panel Display:


The Flat-Panel display refers to a class of video devices that have reduced volume, weight and
power requirement compare to CRT.

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.

2) LED (Light Emitting Diode):

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.

Bit 1:r Bit 2:g Bit 3:b Color name

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:

• Draw a line from A to B


• Draw a line from B to C
• Draw a line from C to D
• Draw a line from D to A
Random-Scan Display Processors: Input in the form of an application program is stored in the
system memory along with graphics package. Graphics package translates the graphic commands
in application program into a display file stored in system memory. This display file is then
accessed by the display processor to refresh the screen. The display processor cycles through
each command in the display file program. Sometimes the display processor in a random-scan is
referred as Display Processing Unit / Graphics Controller. The structure of a simple random scan
is shown below:

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);

It will draw a line from point (10,10) to point (100,100).


Output:
It draws only a line not a box on screen.

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:

6) rectangle(): - This command draws a rectangle on


screen.
Syntax: rectangle(x1, y1, x2, y2);
Where, (x1,y1) are co-ordinates of top-left corner point of
rectangle and(x2,y2) are co-ordinates of bottom-right corner
point of rectangle.
Example: rectangle(10,10,100,100);
It will draw a rectangle as shown in following output.
7) ellipse(): - In draws an ellipse on screen.
Syntax: ellipse(x,y,start,end,xrad,yrad);
Where, (x, y) are co-ordinates of centre point
(start, end) starting and ending angle of ellipse
(xrad, yrad) are x-axis and y-axis radius respectively

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);

8) drawpoly(): - It draws outline of polygon having specified number of sides.


Syntax: drawpoly(n,array);

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);

Where, m is array which stores co-ordinates of vertices of a triangle.


Triangle has three vertices but to close it one vertex is added as a starting andhence number of
vertices are 4. As number of vertices are 4 and each vertex has x,
yco-ordinates (2 values) and hence size of array is 8.
To draw a triangle command will be:
int m[8]={100,100,150,150,50,150,100,100};
drawpoly(4,m);

C. Colors:
9) setcolor(): - it draws any subsequent graphics in a color given in command.
Syntax: setcolor(color);

Where, color is either color constant or color name as specified in tableabove.


Example:
setcolor(RED);
line(10,10,100,100);
It will draw a line in red color.
If it is,
line(10,10,100,100);
setcolor(RED);
It will not draw line in red color.
10) setfillstyle(): - this command decides the filling pattern and the filling color but it do not
actually fill.
Syntax: setfillstyle(pattern,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);

Where, linestyle gives different style of line as shown in table below:

User_defined_style is user defined style and if ignored set to zero.


Line_width is tickness of line as given below

Example: setlinestyle(2,0,3);

This will draw thick centre line as follows:

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;
}

2) C program to draw circle in c graphics


#include <graphics.h>
#include <stdio.h>
int main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, “C\\tc\\bgi);
circle(150,150,90);
getch();
closegraph();
return 0;
}

3) C program to draw drawpoly function


#include <graphics.h>
#include <stdio.h>
int main()
{
int gd=DETECT, gm;
int points[]={150,130,350,130,350,400,250,400,150,130};
initgraph(&gd, &gm, “C\\tc\\bgi);
drawpoly (5, points);
getch();
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.

Advantage of developing algorithms for scan conversion


1. Algorithms can generate graphics objects at a faster rate.
2. Using algorithms memory can be used efficiently.
3. Algorithms can develop a higher level of graphical objects.
Examples of objects which can be scan converted
1. Point
2. Line
3. Sector
4. Arc
5. Ellipse
6. Rectangle
7. Polygon
8. Characters
9. Filled Regions
The process of converting is also called as rasterization. The algorithms implementation varies
from one computer system to another computer system. Some algorithms are implemented using
the software. Some are performed using hardware or firmware. Some are performed using
various combinations of hardware, firmware, and software.

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.

Scan Converting a Point


Each pixel on the graphics display does not represent a mathematical point. Instead, it means a
region which theoretically can contain an infinite number of points. Scan-Converting a point
involves illuminating the pixel that contains the point.
Example: Display coordinates points as shown in fig would both be
represented by pixel (2, 1). In general, a point p (x, y) is represented by the integer part of x &
the integer part of y that is pixels [(INT (x), INT (y).

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.

The primary design criteria are as follows.


• Straight lines appear as straight lines.
• Straight lines start and end accurately.
• Displayed lines should have constant brightness along their length, independent of the
line length and orientation.
• Lines should be drawn rapidly.

Method-1: Direct Method:

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' ).

Then m = (y2',y1')/( x2',x1') and b =

If value of |m|≤1 for each integer value of x. But do not consider

If value of |m|>1 for each integer value of y. But do not consider


Example: A line with starting point as (0, 0) and ending point (6, 18) is given. Calculate value of
intermediate points and slope of line.
Solution: P1 (0,0) P7 (6,18)
x1=0, y1=0
x2=6, y2=18

We know equation of line is


y =m x + b
y = 3x + b..............equation (1)
put value of x from initial point in equation (1), i.e., (0, 0) x =0, y=0
0=3x0+b
0 = b ⟹ b=0
put b = 0 in equation (1)
y = 3x + 0
y = 3x
Now calculate intermediate points
Let x = 1 ⟹ y = 3 x 1 ⟹ y = 3 Let x = 4 ⟹ y = 3 x 4 ⟹ y = 12
Let x = 2 ⟹ y = 3 x 2 ⟹ y = 6 Let x = 5 ⟹ y = 3 x 5 ⟹ y = 15
Let x = 3 ⟹ y = 3 x 3 ⟹ y = 9 Let x = 6 ⟹ y = 3 x 6 ⟹ y = 18

So points are P1 (0,0) , P2 (1,3), P3 (2,6), P4 (3,9), P5 (4,12), P6 (5,15), P7 (6,18)

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

Method-2: DDA (Digital Differential Analyzer) Algorithm:

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=

For calculating next value of x takes x = x +

Program to implement DDA Line Drawing Algorithm:


#include<graphics.h>
#include<conio.h>

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

Substituting m by and introducing decision variable


di=△x (s-t)

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]

Since mx1+b-yi=0 and m = , we have


d1=2△y-△x
Advantage:
1. It involves only integer arithmetic, so it is simple.
2. It avoids the generation of duplicate points.

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:

Differentiate between DDA Algorithm and Bresenham's Line Algorithm:


DDA Algorithm Bresenham's Line Algorithm

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

Thereafter, if d_i<0,then only x is incremented.

xi+1=xi+1 di+1=di+ 4xi+6

& if di≥0,then x & y are incremented


xi+1=xi+1 yi+1 =yi+ 1
di+1=di+ 4 (xi-yi)+10

Bresenham's Circle Algorithm:


Step1: Start Algorithm
Step2: Declare p, q, x, y, r, d variables
p, q are coordinates of the center of the circle
r is the radius of the circle
Step3: Enter the value of r
Step4: Calculate d = 3 - 2r
Step5: Initialize x=0
&nbsy= r
Step6: Check if the whole circle is scan converted
If x > = y
Stop
Step7: Plot eight points by using concepts of eight-way symmetry. The center is at (p, q).
Current active pixel is (x, y).
putpixel (x+p, y+q)
putpixel (y+p, x+q)
putpixel (-y+p, x+q)
putpixel (-x+p, y+q)
putpixel (-x+p, -y+q)

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

Example: Plot 6 points of circle using Bresenham Algorithm. When radius of


circle is 10 units. The circle has centre (50, 50).
Solution: Let r = 10 (Given)
Step1: Take initial point (0, 10)
d = 3 - 2r
d = 3 - 2 * 10 = -17
d < 0 ∴ d = d + 4x + 6
= -17 + 4 (0) + 6
= -11
Step2: Plot (1, 10)
d = d + 4x + 6 (∵ d < 0)
= -11 + 4 (1) + 6
= -1
Advertisement
Step3: Plot (2, 10)
d = d + 4x + 6 (∵ d < 0)
= -1 + 4 x 2 + 6
= 13
Step4: Plot (3, 9) d is > 0 so x = x + 1, y = y - 1
d = d + 4 (x-y) + 10 (∵ d > 0)
= 13 + 4 (3-9) + 10
= 13 + 4 (-6) + 10
= 23-24=-1
Step5: Plot (4, 9)
d = -1 + 4x + 6
= -1 + 4 (4) + 6
= 21
Step6: Plot (5, 8)
d = d + 4 (x-y) + 10 (∵ d > 0)
= 21 + 4 (5-8) + 10
= 21-12 + 10 = 19

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>

void EightWaySymmetricPlot(int xc,int yc,int x,int y)


{
putpixel(x+xc,y+yc,RED);
putpixel(x+xc,-y+yc,YELLOW);
putpixel(-x+xc,-y+yc,GREEN);
putpixel(-x+xc,y+yc,YELLOW);
putpixel(y+xc,x+yc,12);
putpixel(y+xc,-x+yc,14);
putpixel(-y+xc,-x+yc,15);
putpixel(-y+xc,x+yc,6);
}

void BresenhamCircle(int xc,int yc,int r)


{
int x=0,y=r,d=3-(2*r);
EightWaySymmetricPlot(xc,yc,x,y);

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");

/* 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 */
}
printf("Enter the values of xc and yc :");
scanf("%d%d",&xc,&yc);
printf("Enter the value of radius :");
scanf("%d",&r);
BresenhamCircle(xc,yc,r);

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

This is called midpoint (xi+1,yi- ) and we use it to define a decision parameter:

Pi=f (xi+1,yi- ) = (xi+1)2+(yi- )2-r2 ...............equation 2


If Pi is -ve ⟹midpoint is inside the circle and we choose pixel T

If Pi is+ve ⟹midpoint is outside the circle (or on the circle)and we choose pixel S.

The decision parameter for the next step is:

Pi+1=(xi+1+1)2+(yi+1-MidPoint Circle Algorithm)2- r2............equation 3

Since xi+1=xi+1, we have

If pixel T is choosen ⟹Pi<0


We have yi+1=yi
If pixel S is choosen ⟹Pi≥0
We have yi+1=yi-1

45
We can continue to simplify this in n terms of (xi,yi) and get

Now, initial value of Pi (0,r)from equation 2

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

Program to draw a circle using Midpoint 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;
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:

Scan Converting a Ellipse:


The ellipse is also a symmetric figure like a circle but is four-way symmetry rather than eight-
way.

Program to Implement Ellipse Drawing Algorithm:


#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
void disp();
float x,y;
intxc,yc;
void main()
{
intgd=DETECT,gm,a,b;
float p1,p2;
clrscr();
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("*** Ellipse Generating Algorithm ***\n");
printf("Enter the value of Xc\t");
scanf("%d",&xc);

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:

There two methods of defining an Ellipse:


1. Polynomial Method of defining an Ellipse
2. Trigonometric method of defining an Ellipse

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

Drawback of Polynomial Method:


1. It requires squaring of values. So floating point calculation is required.
2. Routines developed for such calculations are very complex and slow.

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

where (h, k) = ellipse center


a = length of the major axis
b = length of the minor axis
In the trigonometric method, the equations are
x = b cos (θ)+h and y=a sin(θ)+k
Where (x, y) = current coordinates
a = length of the major axis
b = length of the minor axis
θ = current angle
(h, k) = ellipse center
Assume that you would like to rotate the ellipse through an angle other than 90 degrees. The
rotation of the ellipse may be accomplished by rotating the x &y axis α degrees.
x = a cos (0) - b sin (0+ ∞) + h y= b (sin 0) + a cos (0+∞) + k

Midpoint Ellipse Algorithm:


This is an incremental method for scan converting an ellipse that is centered at the origin in
standard position i.e., with the major and minor axis parallel to coordinate system axis. It is very
similar to the midpoint circle algorithm. Because of the four-way symmetry property we need to
consider the entire elliptical curve in the first quadrant.
Let's first rewrite the ellipse equation and define the function f that can be used to decide if the
midpoint between two candidate pixels is inside or outside the ellipse:

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=b2 (xi+1)2+a2 (yi- )2-a2 b2


If pi<0, the midpoint is inside the curve and we choose pixel T.
If pi>0, the midpoint is outside or on the curve and we choose pixel S.
Decision parameter for the next step is:

pi+1=f(xi+1+1,yi+1- )

= b2 (xi+1+1)2+a2 (yi+1- )2-a2 b2


Since xi+1=xi+1,we have

pi+1-pi=b2[((xi+1+1)2+a2 (yi+1- )2-(yi - )2]

pi+1= pi+2b2 xi+1+b2+a2 [(yi+1- )2-(yi - )2]


If T is chosen pixel (pi<0), we have yi+1=yi.
If S is chosen pixel (pi>0) we have yi+1=yi-1. Thus we can express

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):

p1 = (b2+a2 (b- )2-a2 b2


= b2-a2 b+a2/4
Suppose the pixel (xj yj) has just been scan converted upon entering step j. The next pixel is
either U (xj ,yj-1) or V (xj+1,yj-1). The midpoint of the horizontal line connecting U & V is used
to define the decision parameter:

qj=f(xj+ ,yj-1)

qj=b2 (xj+ )2+a2 (yj -1)2-a2 b2


If qj<0, the midpoint is inside the curve and we choose pixel V.
If qj≥0, the midpoint is outside the curve and we choose pixel [Link] parameter for
the next step is:

qj+1=f(xj+1+ ,yj+1-1)

= b2 (xj+1+ )2+ a2 (yj+1-1)2- a2 b2


Since yj+1=yj-1,we have

qj+1-qj=b2 [(xj+1+ )2-(xj + )2 ]+a2 (yj+1-1)2-( yj+1)2 ]

qj+1=qj+b2 [(xj+1+ )2-(xj + )2]-2a2 yj+1+a2


If V is chosen pixel (qj<0), we have xj+1=xj.
If U is chosen pixel (pi>0) we have xj+1=xj. Thus we can express
qj+1in terms of qj and (xj+1,yj+1 ):
qj+1=qj+2b2 xj+1-2a2 yj+1+a2 if qj < 0
2 2
=qj-2a yj+1+a if qj>0
The initial value for the recursive expression is computed using the original definition of
qj. And the coordinates of (xk yk) of the last pixel choosen for the part 1 of the curve:

q1 = f(xk+ ,yk-1)=b2 (xk+ )2-a2 (yk-1)2- a2 b2


Algorithm:
int x=0, y=b; [starting point]
int fx=0, fy=2a2 b [initial partial derivatives]
int p = b2-a2 b+a2/4
while (fx<="" {="" set="" pixel="" (x,="" y)="" x++;="" fx="fx" +="" 2b2;
if (p<0)
p = p + fx +b2
;
else
{
y--;
fy=fy-2a2
p = p + fx +b2-fy;

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

Mid-Point Ellipse Algorithm :


1. Take input radius along x axis and y axis and obtain center of ellipse.
2. Initially, we assume ellipse to be centered at origin and the first point as : (x, y0)= (0, ry).
3. Obtain the initial decision parameter for region 1 as: p10=ry2+1/4rx2-rx 2ry
4. For every xk position in region 1 :
If p1k<0 then the next point along the is (xk+1 , yk) and p1k+1=p1k+2ry2xk+1+ry2
Else, the next point is (xk+1, yk-1 )
And p1k+1=p1k+2ry2xk+1 – 2rx2yk+1+ry2
5. Obtain the initial value in region 2 using the last point (x0, y0) of region 1 as:
p20=ry2(x0+1/2)2+rx2 (y0-1)2-rx2ry2
6. At each yk in region 2 starting at k =0 perform the following task.
If p2k>0 the next point is (xk, yk-1) and p2k+1=p2k-2rx2yk+1+rx2
7. Else, the next point is (xk+1, yk -1) and p2k+1=p2k+2ry2xk+1 -2rx2yk+1+rx2
8. Now obtain the symmetric points in the three quadrants and plot the coordinate value as:
x=x+xc, y=y+yc

61
9. Repeat the steps for region 1 until 2ry2x&gt=2rx2y

C program for implementing Mid-Point Ellipse Drawing Algorithm

#include <stdio.h>

void midptellipse(int rx, int ry, int xc, int yc)


{

float dx, dy, d1, d2, x, y;


x = 0;
y = ry;

// Initial decision parameter of region 1


d1 = (ry * ry)
- (rx * rx * ry)
+ (0.25 * rx * rx);
dx = 2 * ry * ry * x;
dy = 2 * rx * rx * y;

// For region 1
while (dx < dy) {

// Print 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);

// Checking and updating value of


// decision parameter based on algorithm
if (d1 < 0) {
x++;
dx = dx + (2 * ry * ry);
d1 = d1 + dx + (ry * ry);
}
else {
x++;
y--;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d1 = d1 + dx - dy + (ry * ry);
}
}

// Decision parameter of region 2


d2 = ((ry * ry) * ((x + 0.5) * (x + 0.5)))
+ ((rx * rx) * ((y - 1) * (y - 1)))
- (rx * rx * ry * ry);

// Plotting points of region 2


while (y >= 0) {

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);

// Checking and updating parameter


// value based on algorithm
if (d2 > 0) {
y--;
dy = dy - (2 * rx * rx);
d2 = d2 + (rx * rx) - dy;
}
else {
y--;
x++;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d2 = d2 + dx - dy + (rx * rx);
}
}
}

// 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

Program line Translation


#include <iostream>
#include <graphics.h>

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");

// drawing original line using graphics functions


setcolor(2);
line(P[0][0], P[0][1], P[1][0], P[1][1]);

// calculating translated coordinates


P[0][0] = P[0][0] + T[0];
P[0][1] = P[0][1] + T[1];
P[1][0] = P[1][0] + T[0];
P[1][1] = P[1][1] + T[1];

// drawing translated line using graphics functions


setcolor(3);
line(P[0][0], P[0][1], P[1][0], P[1][1]);
closegraph();
}

// 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;
}

Program Rectangle Translation


#include <graphics.h>
#include <iostream>

// Function to translate rectangle


void translateRectangle(int P[][2], int T[])
{
int gd = DETECT, gm, errorcode;
initgraph(&gd, &gm,
"c:\\tc\\bgi"); // Initialize graphics

// Original rectangle

66
setcolor(2);
rectangle(P[0][0], P[0][1], P[1][0], P[1][1]);

// Calculating translated coordinates


P[0][0] = P[0][0] + T[0];
P[0][1] = P[0][1] + T[1];
P[1][0] = P[1][0] + T[0];
P[1][1] = P[1][1] + T[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

Representing the above equation in matrix form,

Where R is the rotation matrix

The rotation angle can be positive and negative.


For positive rotation angle, we can use the above rotation matrix. However, for negative angle
rotation, the matrix will change as shown below –

program for rotating a 2D triangle using rotation transformation


techniques:
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>

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;

initgraph(&gd, &gm, "");

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);

DrawTriangle(x1, y1, x2, y2, x3, y3);

printf("Enter the angle for rotation (in degrees): ");


scanf("%f", &angle);

RotateTriangle(x1, y1, x2, y2, x3, y3, angle);

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;

int a1 = p + (x1 - p) * cos(radianAngle) - (y1 - q) * sin(radianAngle);


int b1 = q + (x1 - p) * sin(radianAngle) + (y1 - q) * cos(radianAngle);

int a2 = p + (x2 - p) * cos(radianAngle) - (y2 - q) * sin(radianAngle);


int b2 = q + (x2 - p) * sin(radianAngle) + (y2 - q) * cos(radianAngle);

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.

Program of Scaling Transformation


#include <stdio.h>
#include <conio.h>
#include <graphics.h>
70
#include <process.h>
#include <math.h>

int x1, y1, x2, y2, x3, y3;

void draw();
void scale();

void main()
{
int gd = DETECT, gm;
int c;
initgraph(&gd, &gm, " ");

printf("Enter the 1st point for the triangle:");


scanf("%d%d", &x1, &y1);

printf("Enter the 2nd point for the triangle:");


scanf("%d%d", &x2, &y2);

printf("Enter the 3rd point for the triangle:");


scanf("%d%d", &x3, &y3);

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;

printf("Enter the scaling factors (x y): ");


scanf("%d%d", &x, &y);

mx = (x1 + x2 + x3) / 3;
my = (y1 + y2 + y3) / 3;

71
cleardevice();

int a1, a2, a3, b1, b2, b3;


a1 = mx + (x1 - mx) * x;
b1 = my + (y1 - my) * y;
a2 = mx + (x2 - mx) * x;
b2 = my + (y2 - my) * y;
a3 = mx + (x3 - mx) * x;
b3 = my + (y3 - my) * y;

line(a1, b1, a2, b2);


line(a2, b2, a3, b3);
line(a3, b3, a1, b1);

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

3. Reflection about an axis perpendicular to xy plane and passing through origin:


In the matrix of this transformation is given below

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°.

Example: A triangle ABC is given. The coordinates of A, B, C are given as


A (3 4)
B (6 4)
C (4 8)
Find reflected position of triangle i.e., to the x-axis.

74
Solution:

The a point coordinates after reflection

The b point coordinates after reflection

The coordinate of point c after reflection

a (3, 4) becomes a1 (3, -4)


b (6, 4) becomes b1 (6, -4)
c (4, 8) becomes c1 (4, -8)

75

You might also like