Professional Documents
Culture Documents
DMC1937
DMC1937
DMC1937
(DISTANCE MODE)
DMC 1757
Graphics and Multimedia Laboratory
IV SEMESTER
LAB MATERIAL
Author
Ms. T. Mala
Lecturer
Department of Computer Science and Engineering
Anna University Chennai
Chennai - 600 025
Reviewer
Mr. T. Raghuveera
Lecturer
Department of Computer Science and Engineering
Anna University Chennai
Chennai - 600 025
Editorial Board
Copyrights Reserved
(For Private Circulation only)
2. Write a C program for Line drawing using Bresenham, DDA Line Drawing
Algorithms.
8. Develop a presentation for a product using techniques like Guide Layer, masking
and onion Skin using authoring tools.
10. Demonstrate Rasterization and filtering of layers and give blending effects for a
logo
1. Introduction
3. Line Drawing
3.1 Digital Differential Analyzer
3.2 Bresenhams Algorithm
3.3. Line Attributes
5. Clipping Algorithm
5.1 Line clipping
5.2 Polygon Clipping
Appendix
1. Introduction
This laboratory manual is written to accompany the Graphics and Multimedia Lab
course for the MCA Distance Education Programme of Anna University. The first part of
the manual consists of graphics algorithms with programs for drawing the line, circle and
for implementing various transformations. The graphics part of the manual helps in
understanding the basics behind graphical drawings and also explains the principles
behind all drawing functions. The second part of the manual deals with multimedia where
two multimedia tools are introduced namely an authoring tool and an image editing tool.
2.1 Introduction
There are generally two modes available in C graphics namely text and graphics.
We have the following adapters to generate graphics namely CGA (Color Graphics
Adapter), EGA and VGA.When you consider the graphics mode pixel being a picture
element has a color associated with it. But the way these colors are used depends on
adapters because each adapter differs in the way they handle colors and also in the
number of colors supported.
Having known about adapters, now let us start knowing on how to start switching
to graphics mode from text mode in other words how to start using pixel and resolution
concepts. This is done by a function called initgraph( ). This initgraph( ) takes in it two
main arguments as input namely gd and gm. In this gd has the number of mode which has
the best resolution. This is very vital for graphics since the best resolution only gives a
sharper picture as we have seen before. This value is obtained by using the function
called as getgraphmode( ) in C graphics. The other argument gm gives insight about the
monitor used, the corresponding resolution of that, the colors that are available since this
varies based on adapters supported. This value is obtained by using the function named as
getmodename( ) in C graphics.
InitGraph:
Initgraph() function initializes the graphics mode and clears the screen. To start
the graphics system, you must first call initgraph. initgraph initializes the graphics system
by loading a graphics driver from disk (or validating a registered driver) and then putting
the system into graphics mode. Initgraph also resets all graphics settings (color, palette,
current position, viewport, etc.) to their defaults, then resets graph result to 0.
Declaration:
void far initgraph(int far *graphdriver, int far *graphmode, char far
*pathtodriver);
Arguments:
*graphdriver: Integer that specifies the graphics driver to be used. You can give
graphdriver a value using a constant of the graphics drivers enumeration type.
*graphmode : Integer that specifies the initial graphics mode (unless *graphdriver
= DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest
resolution available for the detected driver. You can give *graphmode a value using a
constant of the graphics_modes enumeration type. If you have the BGI file in the same
folder of your program, you can just leave it as "" only. You need not mention
*graphmode if you give *graphdriver as DETECT.
pathtodriver : Specifies the directory path where initgraph looks for graphics
drivers (*.BGI) first. If they're not there, initgraph looks in the current directory. If
pathtodriver is null, the driver files must be in the current directory. This is also the path
settextstyle searches for the stroked character font files (*.CHR).
There are numerous graphics functions available in C. But let us see some of the
functions to have an understanding of how and where a pixel is placed in each when each
of the graphics function gets invoked.
Function :
putpixel(x, y, color)
Purpose:
Function :
getpixel(x, y)
Purpose:
This function when invoked gets the color of the pixel specified. The color got
will be the integer value associated with that color and hence the function gets an integer
value as return value.
Example Program 1:
To run this program, you need graphics.h header file, graphics.lib library file
and Graphics driver (BGI file) in the program folder. These files are part of Turbo C
package. In all the programs listed here we use 640x480 VGA resolution.You need to
make necessary changes to your programs according to your screen resolution. For VGA
monitor, graphics driver used is EGAVGA.BGI.
Output:
Function :
closegraph()
Purpose:
Switches back the screen from graphics mode to text mode. It clears the screen
also. A graphics program should have a closegraph function at the end of graphics.
Otherwise DOS screen will not go to text mode after running the program. Here,
closegraph() is called after getch() since screen should not clear until user hits a key.
In graphics mode, all the screen co-ordinates are mentioned in terms of pixels.
Number of pixels in the screen decides resolution of the screen. In the example program
1, circle is drawn with x-coordinate of the center 100, y-coordinate 100 and radius 50
pixels. All the coordinates are mentioned with respect to top-left corner of the screen.
Example Program 2:
#include<graphics.h>
#include<conio.h>
void main()
{
int gd=DETECT, gm;
int poly[12]={350,450, 350,410, 430,400, 350,350, 300,430, 350,450 };
initgraph(&gd, &gm, "");
circle(100,100,50);
outtextxy(75,170, "Circle");
rectangle(200,50,350,150);
outtextxy(240, 170, "Rectangle");
ellipse(500, 100,0,360, 100,50);
outtextxy(480, 170, "Ellipse");
line(100,250,540,250);
outtextxy(300,260,"Line");
Output:
Function :
void far line(int x1, int y1, int x2, int y2)
Purpose:
The functionality is to draw a line from (x1,y1) to (x2,y2). Here also the
coordinates are passed taking the pixel (0,0) at the top left hand corner of the screen as
the origin. And also one must note that the line formed is by using number of pixels
placed near each other.
Function :
Purpose:
outtextxy displays a string in graphical mode. You can use different fonts, text
sizes, alignments, colors and directions of the text. Parameters passed are x and y
coordinates of the position on the screen where text is to be displayed. There is another
function outtext() that displays a text in the current position. Current position is the place
where last drawing has ended. There are functions for drawing circle with its attributes.
Circle, arc, and pieslice are declared as follows:
Function Declaration:
• void far arc(int x, int y, int stangle, int endangle, int radius);
• void far circle(int x, int y, int radius);
• void far pieslice(int x, int y, int stangle, int endangle, int radius);
Purpose:
Arguments:
Here, stangle and endangle are in degrees starting from the +ve x-axis in the polar
coordinate system in the anti-clockwise direction. If stangle is 0, endangle is 360, it will
draw a full circle
Another basic shape that we come across is a rectangle. To draw a border, use
rectangle with the coordinates of outline, to draw a square use rectangle with same height
and width. drawpoly() and fillpoly() are two functions useful to draw any polygons. To
use these functions, store coordinates of the shape in an array and pass the address of
array as an argument to the function. By looking at the output of the previous program,
you can understand what drawpoly is. fillpoly is similar except that it fills in the shape
with current fill color.
Function Declaration:
• void far rectangle(int left, int top, int right, int bottom);
• void far drawpoly(int numpoints, int far *polypoints);
• void far fillpoly(int numpoints, int far *polypoints);
Purpose:
• rectangle draws a rectangle in the current line style, thickness, and drawing color.
• drawpoly draws a polygon using the current line style and color.
• fillpoly draws the outline of a polygon using the current line style and color, then fills
the polygon using the current fill pattern and fill color.
Arguments:
(left,top) is the upper left corner of the rectangle, and (right,bottom) is its lower
right corner.
To draw a closed polygon with N points, numpoints should be N+1 and the array
polypoints[] should contain 2(N+1) integers with first 2 integers equal to last 2 integers.
Here is some idea about colors. There are 16 colors declared in graphics.h as listed below.
Black 0
Blue 1
Green 2
Cyan 3
Red 4
Magenta 5
Brown 6
Lightgray 7
Darkgray 8
Lightblue 9
Lightgreen 10
Lightcyan 11
Lightred 12
Lightmagenta 13
Yellow 14
White 15
setcolor() function sets the current drawing color based on table 1. If we use
setcolor(RED); and draw any shape, line or text after that, the drawing will be in red
color. You can either use color as defined above or number like setcolor(4); setbkcolor()
sets background color for drawing. Setfillstyle sets fill pattern and fill colors. After
calling setfillstyle, if we use functions like floodfill, fillpoly, bar etc, shapes will be filled
with fill color and pattern set using setfillstyle. The function declarations are as follows.
Function Declaration:
Purpose:
Here is an example program with colors, pixels, bar, cleardevice etc. stdlib.h is
used for random number generation. We have a function random(no), it returns a random
number between 0 and 1. The effect is by drawing random radius, random color circles
with same center and random pixels. kbhit() function(defined in conio.h) returns a
nonzero value when a key is pressed in the keyboard. So, the loop will continue until a
key is pressed. Example programs using the above functions are given in the appendix.
Exercises:
1. Draw line graph for the given data using the graphics functions.
RAJ 80 70 65 75 100 80
HARI 30 40 10 45 25 10
The goal of any line drawing algorithm is to construct the best possible
approximation of an ideal line given the inherent limitations of a raster display.
Following is a list of some of line qualities that are often considered.
• Continuous appearance
• Uniform thickness and brightness
• Are the pixels nearest the ideal line turned on
• How fast is the line generated
The first line-drawing algorithm presented is called the simple Digital differential
analyser. It is a straight forward implementation of the slope-intercept formula for a line.
Algorithm:
Given two points (x1, y1) and (x2, y2) that lie on a line, we can solve for m and b for
the line.
Consider y1 = mx1 + b and y2 = mx2 + b.
Subtract y1 from y2 to solve for m =( y2 – y1) / (x2 – x1)
and b = y1 − mx1.
Substituting in the value for b, the line equation can be written as y = m(x − x1) + y1.
Program DDA:
#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>
void main()
{
int gdriver=DETECT,gmode,errorcode;
int x1,y1,x2,y2,k=0;
float dx,dy,steps,xinc,yinc,x,y,px,py;
initgraph(&gdriver,&gmode,"");
printf("Enter x1,y1:");
scanf("%d%d",&x1,&y1);
printf("Enter x2,y2:");
scanf("%d%d",&x2,&y2);
dx=x2-x1;
dy=y2-y1;
steps=dx>dy?abs(dx):abs(dy);
xinc=dx/steps;
yinc=dy/steps;
clrscr();
x=x1;
y=y1;
for(;k<=steps;k++)
{
x+=xinc;
y+=yinc;
px=(int)x;
py=(int)y;
putpixel(px,py,0);
}
getch();
closegraph();
}
Output:
Algorithm:
The below algorithm is for slope 0 < m <= 1. For lines with m > 1 we have to step
along y in unit steps and calculate successive x values. If the initial position of the line is
right end point then both x and y decreases as we step from right to left. For negative
slopes it is the same except that one co ordinate decreases while the other increases. All
the four cases are considered in the given program code.
Program Bresenham:
#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>
void main()
{
int gdriver=DETECT,gmode,errorcode;
int x1,y1,x2,y2,k=0,dx,dy,p;
initgraph(&gdriver,&gmode, "E:\\TC\\BGI");
printf("Enter x1,y1:");
scanf("%d%d",&x1,&y1);
printf("Enter x2,y2:");
scanf("%d%d",&x2,&y2);
dx=x2-x1;
dy=y2-y1;
p=2*abs(dy)-abs(dx);
clrscr();
if(dx==0)
{
for(k=0;k<abs(dy);k++)
{
putpixel(x1,y1,0);
if(dy>0)
y1++;
else
y1--;
}
}
for(;k<=abs(dx);k++)
{
if(p<0)
{
if(dx>0)
x1++;
else
x1--;
p+=2*abs(dy);
}
else
{
if(dx>0)
x1++;
else
x1--;
if(dy>0)
y1++;
else
y1--;
p+=2*abs(dy)-2*abs(dx);
}
putpixel(x1,y1,0);
}
getch();
closegraph();
}
Output:
All lines are associated with line colour, width and style attributes. You can set
the width of the line, the line style say dotted, dashed, solid and the line colour. The
program given below uses all the attributes to display the line.
#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
void line1(int x1,int y1,int x2,int y2,int t, int c, int ty1);
void main()
{
int gdriver=DETECT,gmode,errorcode;
int x1,y1,x2,y2,t,c,ty,ty1;
initgraph(&gdriver,&gmode, "E:\\TC\\BGI");
printf("Enter x1,y1:");
scanf("%d%d",&x1,&y1);
printf("Enter x2,y2:");
scanf("%d%d",&x2,&y2);
printf("Enter thickness:");
scanf("%d",&t);
printf("Enter colour as int:");
scanf("%d",&c);
printf("Enter type:\n 1 - Regular\n 2 - Dotted\n 3 - Dashed\n");
scanf("%d",&ty);
if(ty==3)
ty1=2*t;
else if(ty==2)
ty1=t;
else
ty1=max((x2-x1),(y2-y1));
line1(x1,y1,x2,y2,t,c,ty1);
getch();
closegraph();
}
void line1(int x1,int y1,int x2,int y2,int t,int c,int ty1)
{
int k=0,dx,dy,p,a,b=0;
dx=x2-x1;
dy=y2-y1;
p=2*abs(dy)-abs(dx);
clearviewport();
if(dx==0)
{
for(k=0;k<abs(dy);k++)
{
b++;
if(b<=ty1)
for(a=0;a<t;a++)
putpixel(x1+a,y1,c);
if(b==2*ty1)
b=0;
if(dy>0)
y1++;
else
y1--;
}
}
for(;k<=abs(dx);k++)
{
b++;
if(p<0)
{
if(dx>0)
x1++;
else
x1--;
p+=2*abs(dy);
}
else
{
if(dx>0)
x1++;
else
x1--;
if(dy>0)
y1++;
else
y1--;
p+=2*abs(dy)-2*abs(dx);
}
if(b<=ty1-1)
for(a=0;a<t;a++)
putpixel(x1+a,y1,c);
if(b==2*ty1)
b=0;
}
}
Output:
Exercises:
1. Create a bar chart for the following data by using DDA line drawing algorithm.
Places Temperature
Chennai 35
Madurai 40
Trichy 40
Kodai 25
2. Write program in C to draw polygons with different colours getting the vertices
from the user and use bresenhams line drawing algorithm for drawing the edges.
– Reason from octants of a circle centered in (0,0), then find the remaining
octants by symmetry, then translate to (xc, yc).
– The circle function is the decision parameter.
– Calculate the circle function for the midpoint between two pixels.
Algorithm:
1. Input radius r and circle center (xc, yc), then set the coordinates for the first point
on the circumference of a circle centered on the origin as (x0, y0) = (0, r).
2. Calculate the initial value of the decision parameter as p0 = 5/4 – r (1 – r if an
integer)
3. At each xk, from k=0, perform the following test: if pk<0, next point to plot along
the circle centered on (0,0) is (xk + 1, yk) and pk+1 = pk + 2 xk+1 + 1 otherwise, next
point to plot is (xk+ 1, yk - 1) and pk+1 = pk + 2 xk+1 + 1 - 2 yk+1 where 2xk+1 = 2 xk
+ 2, and 2 yk+1 = 2 yk - 2
4. Determine symmetry points in the other seven octants.
5. Move each calculated pixel position (x, y) onto the circular path centered at (xc,
yc) and plot the coordinate values: x = x + xc, y = y + yc
6. Repeat steps 3 through 5 until x >= y.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
int xc,yc,x,y,r,p;
initgraph(&gd,&gm,"");
printf("Enter the centre and radius : ");
scanf("%d %d %d",&xc,&yc,&r);
p=1-r;
x=0;
y=r;
while(x<y)
{
putpixel(xc+x,yc+y,6);
putpixel(xc-x,yc+y,6);
putpixel(xc+x,yc-y,6);
putpixel(xc-x,yc-y,6);
putpixel(xc+y,yc+x,6);
putpixel(xc-y,yc+x,6);
putpixel(xc+y,yc-x,6);
putpixel(xc-y,yc-x,6);
if(p<0)
x++;
else
{
x++;
y--;
}
if(p<0)
p=p+2*x+1;
else
p=p+2*(x-y)+1;
}
getch();
}
Output:
You can also add attributes to the generated circle. The circle attributes include
circle style and inner fill style. Below is given an example program for implementing
circle attributes using mid point circle generating algorithm.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<graphics.h>
void dott(int xc,int yc,int x,int y,int i, int j)
{
i=2;
if(j%i!=0)
{
putpixel(xc+x,yc+y,6);
putpixel(xc-x,yc+y,6);
putpixel(xc+x,yc-y,6);
putpixel(xc-x,yc-y,6);
putpixel(xc+y,yc+x,6);
putpixel(xc-y,yc+x,6);
putpixel(xc+y,yc-x,6);
putpixel(xc-y,yc-x,6);
}
}
void dash(int xc,int yc,int x,int y,int i,int j)
{ if(j%i!=0)
{
putpixel(xc+x,yc+y,6);
putpixel(xc-x,yc+y,6);
putpixel(xc+x,yc-y,6);
putpixel(xc-x,yc-y,6);
putpixel(xc+y,yc+x,6);
putpixel(xc-y,yc+x,6);
putpixel(xc+y,yc-x,6);
putpixel(xc-y,yc-x,6);
}
}
void thick(int xc,int yc,int x,int y,int t)
{ int l;
for(l=0;l<t;l++)
{
putpixel(xc+x,yc+y+l,6);
putpixel(xc-x,yc+y+l,6);
putpixel(xc+x,yc-y+l,6);
putpixel(xc-x,yc-y+l,6);
putpixel(xc+y,yc+x+l,6);
putpixel(xc-y,yc+x+l,6);
putpixel(xc+y,yc-x+l,6);
putpixel(xc-y,yc-x+l,6);
}
}
int n;
void main()
{
int gd=DETECT,gm; int cho;
int xc,yc,x,y,r,p;
int i,j,t,n;
n=5;
j=1;
while(n==5)
{
initgraph(&gd,&gm,"");
printf("\nEnter the centre and radius : ");
scanf("%d %d %d",&xc,&yc,&r);
printf("\nenter the attribute:");
printf("\n1.dott");
printf("\n2.dash");
printf("\n3.thick");
scanf("%d",&cho);
if(cho==2)
{
printf("\nenter the dash length:");
scanf("%d",&i);
}
if(cho==3)
{
printf("\nenter the thickness");
scanf("%d",&t);
}
p=1-r;
x=0;
y=r;
while(x<y)
{
if(cho==1)
dott(xc,yc,x,y,i,j);
if(cho==2)
dash(xc,yc,x,y,i,j);
if(cho==3)
thick(xc,yc,x,y,t);
j++;
if(p<0)
x++;
else
{
x++;
y--;
}
if(p<0)
p=p+2*x+1;
else
p=p+2*(x-y)+1;
}
getch();
printf("enter 5 to continue and 0 to quit");
scanf("%d",&n);
}
Output:
A sample program for drawing ellipse is given below. Curves and other curve
sections can be drawn based on the below algorithm.
Algorithm:
end while
// Set initial values in region II
P = P – (a2(4y – 3) + b2(4x + 3) + 2) / 4 // Intentionally +2 to round off the value
∆PS = a2(3 – 2y)
∆PSE = 2b2 + 3a2
∆2PS = 2a2
// Plot the pixels in region II
while y > 0
if P > 0 then // Select S
P = P + ∆PE
∆PE = ∆PE + ∆2PS
∆PSE = ∆PSE + ∆2PS
else // Select SE
P = P + ∆PSE
∆PE = ∆PE + ∆2PS
∆PSE = ∆PSE + ∆2PSE
increment x
end if
decrement y
PlotEllipse(xC, yC, x, y)
end while
end DrawEllipse
Program Ellipse:
#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>
void main()
{
int gdriver=DETECT,gmode,errorcode;
float xc,yc,rx,ry,x,y;
float p;
initgraph(&gdriver,&gmode,"");
printf("Enter xc,yc:");
scanf("%f%f",&xc,&yc);
printf("Enter rx and ry:");
scanf("%f%f",&rx,&ry);
x=0;
y=ry;
p=ry*ry-rx*rx*ry+rx*rx/4;
cleardevice();
putpixel(xc+x,yc+y,3);
putpixel(xc-x,yc-y,3);
putpixel(xc-x,yc+y,3);
putpixel(xc+x,yc-y,3);
while(ry*ry*x<rx*rx*y)
{
if(p<0)
{
x++;
p+=2*ry*ry*x+ry*ry;
}
else
{
x++;
y--;
p+=2*ry*ry*x+ry*ry-2*rx*rx*y;
}
putpixel(xc+x,yc+y,3);
putpixel(xc-x,yc-y,3);
putpixel(xc-x,yc+y,3);
putpixel(xc+x,yc-y,3);
}
p=ry*ry*(x+0.5)*(x+0.5)+rx*rx*(y-1)*(y-1)-rx*rx*ry*ry;
putpixel(xc+x,yc+y,3);
putpixel(xc-x,yc-y,3);
putpixel(xc-x,yc+y,3);
putpixel(xc+x,yc-y,3);
while(y>0)
{
if(p>0)
{
y--;
p+=-2*rx*rx*y+rx*rx;
}
else
{
x++;
y--;
p+=-2*rx*rx*y+rx*rx+2*ry*ry*x;
}
putpixel(xc+x,yc+y,3);
putpixel(xc-x,yc-y,3);
putpixel(xc-x,yc+y,3);
putpixel(xc+x,yc-y,3);
}
getch();
closegraph();
}
Output:
Exercises:
• Draw concentric circles of different circle style using mid point circle drawing
algorithm.
• Write a program in C to implement attributes in ellipse using mid point ellipse
drawing algoritghm.
5. Clipping Algorithm
There are various line clipping algorithms available. Cohen Sutherland line
clipping and Liang Barsky line clipping algorithms are explained below.
Algorithm:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
int xmin=50,ymin=100,ymax=350,xmax=350;
int code[12];
int x[12]={120,250,150,220,430,500,20,200,300,330,200,425};
int y[12]={120,250,70,150,400,600,20,300,280,450,175,300};
void clip(int x1,int y1,int x2,int y2)
{
int i,t;
for(i=0;i<=1;i++)
{
if(x1<xmin)
{
y1=((xmin-x1)*(y2-y1)/(x2-x1))+y1;
x1=xmin;
}
else if(x1>xmax)
{
y1=((xmax-x1)*(y2-y1)/(x2-x1))+y1;
x1=xmax;
}
if(y1<ymin)
{
x1=((ymin-y1)*(x2-x1)/(y2-y1))+x1;
y1=ymin;
}
else if(y1>ymax)
{
x1=((ymax-y1)*(x2-x1)/(y2-y1))+x1;
y1=ymax;
}
t=x1;
x1=x2;
x2=t;
t=y1;
y1=y2;
y2=t;
}
line(x1,y1,x2,y2);
}
void main()
{
int gdriver=DETECT,gmode,errorcode;
int i;
initgraph(&gdriver,&gmode, "");
clearviewport();
rectangle(xmin,ymin,xmax,ymax);
printf("Before clipping:");
for(i=0;i<12;i+=2)
line(x[i],y[i],x[i+1],y[i+1]);
getch();
clearviewport();
printf("After clipping:");
for(i=0;i<12;i++)
{
code[i]=0;
if(x[i]<xmin)
code[i]+=1;
if(x[i]>xmax)
code[i]+=2;
if(y[i]<ymin)
code[i]+=4;
if(y[i]>ymax)
code[i]+=8;
}
for(i=0;i<12;i+=2)
{
if(code[i]==0 && code[i+1]==0)
line(x[i],y[i],x[i+1],y[i+1]);
else
if((code[i]&code[i+1])==0)
clip(x[i],y[i],x[i+1],y[i+1]);
}
rectangle(xmin,ymin,xmax,ymax);
getch();
closegraph();
}
Output:
Liang Barsky:
Algorithm:
The idea of the L-B clipping algorithm is to do as much testing as possible before
computing line intersections. Consider first the usual parametric form of a straight line:
x = x0 + u (x1 - x0) = x0 + u ∆x
y = y0 + u (y1 - y0) = y0 + u ∆y
A point is in the clip window if
xmin ≤ x0 + u ∆x ≤ xmax
ymin ≤ y0 + u ∆y ≤ ymax
which can be expressed as the 4 inequalities
u pk ≤ qk where k = 1, 2, 3, 4
where p1 = -∆x q1 = x0 - xmin (left)
p2 = ∆x q2 = xmax - x0 (right)
p3 = -∆y q3 = y0 - ymin (bottom)
p4 = ∆y q4 = ymax - y0 (top)
#include<graphics.h>
#include<dos.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int gd, gm ;
int x1 , y1 , x2 , y2 ;
int wxmin,wymin,wxmax, wymax ;
float u1 = 0.0,u2 = 1.0 ;
int p1 , q1 , p2 , q2 , p3 , q3 , p4 ,q4 ;
float r1 , r2 , r3 , r4 ;
int x11 , y11 , x22 , y22 ;
clrscr();
printf("Enter the windows left xmin , top boundry ymin\n");
scanf("%d%d",&wxmin,&wymin);
printf("Enter the windows right xmax ,bottom boundry ymax\n");
scanf("%d%d",&wxmax,&wymax);
printf("Enter line x1 , y1 co-ordinate\n");
scanf("%d%d",&x1,&y1);
printf("Enter line x2 , y2 co-ordinate\n");
scanf("%d%d",&x2,&y2);
printf("liang barsky express these 4 inequalities using lpk<=qpk\n");
p1 = -(x2 - x1 ); q1 = x1 - wxmin ;
p2 = ( x2 - x1 ) ; q2 = wxmax - x1 ;
p3 = - ( y2 - y1 ) ; q3 = y1 - wymin ;
p4 = ( y2 - y1 ) ; q4 = wymax - y1 ;
printf("p1=0 line is parallel to left clipping\n");
printf("p2=0 line is parallel to right clipping\n");
printf("p3=0 line is parallel to bottom clipping\n");
printf("p4=0 line is parallel to top clipping\n");
if( ( ( p1 == 0.0 ) && ( q1 < 0.0 ) ) ||
( ( p2 == 0.0 ) && ( q2 < 0.0 ) ) ||
( ( p3 == 0.0 ) && ( q3 < 0.0 ) ) ||
( ( p4 == 0.0 ) && ( q4 < 0.0 ) ) )
{
printf("Line is rejected\n");
getch();
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\tc\\bgi");
setcolor(CYAN);
rectangle(wxmin,wymax,wxmax,wymin);
setcolor(BLUE);
line(x1,y1,x2,y2);
getch();
setcolor(WHITE);
line(x1,y1,x2,y2);
getch();
}
else
{
if( p1 != 0.0 )
{
r1 =(float) q1 /p1 ;
if( p1 < 0 )
u1 = max(r1 , u1 );
else
u2 = min(r1 , u2 );
}
if( p2 != 0.0 )
{
r2 = (float ) q2 /p2 ;
if( p2 < 0 )
u1 = max(r2 , u1 );
else
u2 = min(r2 , u2 );
}
if( p3 != 0.0 )
{
r3 = (float )q3 /p3 ;
if( p3 < 0 )
u1 = max(r3 , u1 );
else
u2 = min(r3 , u2 );
}
if( p4 != 0.0 )
{
r4 = (float )q4 /p4 ;
if( p4 < 0 )
u1 = max(r4 , u1 );
else
u2 = min(r4 , u2 );
}
if( u1 > u2 )
printf("line rejected\n");
else
{
x11 = x1 + u1 * ( x2 - x1 ) ;
y11 = y1 + u1 * ( y2 - y1 ) ;
x22 = x1 + u2 * ( x2 - x1 );
y22 = y1 + u2 * ( y2 - y1 );
printf("Original line cordinates\n");
printf("x1 = %d , y1 = %d, x2 = %d, y2 = %d\n",x1,y1,x2,y2);
printf("Windows coordiante are \n");
printf("wxmin = %d, wymin = %d,wxmax = %d , wymax = %d",
wxmin,wymin,wxmax,wymax);
printf("New coordinates are \n");
printf("x1 = %d, y1 = %d,x2 = %d , y2 = %d\n",x11,y11,x22,y22);
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"C:\\TC\\BGI");
setcolor(2);
rectangle(wxmin,wymax,wxmax,wymin);
setcolor(1);
line(x1,y1,x2,y2);
getch();
setcolor(0);
line(x1,y1,x2,y2);
setcolor(3);
line(x11,y11,x22,y22);
getch();
}
}
}
Output:
Algorithm
Given a clip window edge and a subject polygon edge, there are four cases to consider:
1. The subject polygon edge goes from outside clip window edge to outside clip
window edge. In this case we output nothing.
2. The subject polygon edge goes from outside clip window edge to inside clip
window edge. In this case we save intersection and inside vertex.
3. The subject polygon edge goes from inside clip window edge to outside clip
window edge. In this case we save intersection point.
4. The subject polygon edge goes from inside clip window edge to inside clip
window edge. In this case we save second inside point (the first was saved
previously).
5. In the given code the widow size is specified as (xmin, ymin) and (xmax, ymax).
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
int xmin=20,ymin=20,ymax=100,xmax=100;
int x[10];
int y[10];
int ver,j=0,col=5;
int xc[15],yc[15],pos[5],b=0;
void polyfill()
{
int i,k,cnt=0;
for(i=0;i<=getmaxx();i++)
{
cnt=0;
for(k=0;k<=getmaxy();k++)
{
if(getpixel(i,k)==col)
cnt++;
if(cnt%2==1)
putpixel(i,k,col);
}
}
}
void drawpolygon()
{
int i;
setcolor(5);
for(i=0;i<ver;i++)
line(x[i],y[i],x[(i+1)%ver],y[(i+1)%ver]);
}
yc[j+1]=y2;
//out to in
//in to out
if(x1>=xmin && x2<=xmin)
{
if(x1!=x2)
y2=(xmin-x2)*(y1-y2)/(x1-x2)+y2;
x2=xmin;
a=1;
}
else if(x1<=xmax && x2>=xmax)
{
if(x1!=x2)
y2=(xmax-x2)*(y1-y2)/(x1-x2)+y2;
x2=xmax;
a=1;
}
if(y1>=ymin && y2<=ymin)
{
if(y1!=y2)
x2=(ymin-y2)*(x1-x2)/(y1-y2)+x2;
y2=ymin;
a=1;
}
else if(y1<=ymax && y2>=ymax)
{
if(x1!=x2)
x2=(ymax-y2)*(x1-x2)/(y1-y2)+x2;
y2=ymax;
a=1;
}
if(a==1)
{
xc[j]=x1;
yc[j]=y1;
yc[j+1]=y2;
xc[j+1]=x2;
}
line(xc[j],yc[j],xc[(j+1)],yc[(j+1)]);
if(a==1)
pos[b++]=j+1;
j+=2;
}
void main()
{
int gdriver=DETECT,gmode,errorcode;
int i=0;
initgraph(&gdriver,&gmode, "");
clearviewport();
printf("Enter the no. of vertices:");
scanf("%d",&ver);
printf("Enter the vertices:");
for(i=0;i<ver;i++)
scanf("%d%d",&x[i],&y[i]);
printf("Before clipping");
rectangle(xmin,ymin,xmax,ymax);
drawpolygon();
getch();
clearviewport();
printf("After clipping");
setcolor(15);
rectangle(xmin,ymin,xmax,ymax);
setcolor(5);
for(i=0;i<ver;i++)
{
polyclip(x[i],y[i],x[(i+1)%ver],y[(i+1)%ver]);
}
for(i=0;i<b;i++)
{
line(xc[pos[i]],yc[pos[i]],xc[(pos[i]+1)%(j)],yc[(pos[i]+1)%(j)]);
}
getch();
closegraph();
}
Output:
Exercises:
There are three basic transformations that can be applied over objects namely the
Translation, Rotation and the Scaling. Other transformations like reflection and shear can
also be considered for object transformations. These transformations can be applied over
two and three dimensional objects.
Algorithm:
A point (x1,y1) is transformed to location (x2,y2) after applying the basic transformations.
Translation
x2 = x 1 + t x
y2 = y1 + ty
Scaling
x2 = ax*x1
y2 = ay*y1
Rotation
x2 = x1*cos(a) + y1*sin(a)
y2 = - x1*sin(a) + y1*cos(a)
Program Transformation:
#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
int col=3;
void matmul(float **x,float **y,float **res)
{
int i,j,k,r;
for(i=0;i<3;i++)
{
r=0;
for(j=0;j<3;j++)
{
r+=x[i][j]*y[j][0];
}
res[i][0]=r;
}
}
void line1(int x1,int y1,int x2,int y2)
{
int dx,dy,p,k=0;
dx=x2-x1;
dy=y2-y1;
p=2*abs(dy)-abs(dx);
if(dx==0)
{
for(k=0;k<abs(dy);k++)
{
putpixel(x1,y1,col);
if(dy>0 )
y1++;
else
y1--;
}
}
for(;k<=abs(dx);k++)
{
if(p<0)
{
if(dx>0)
x1++;
else
x1--;
p+=2*abs(dy);
}
else
{
if(dx>0)
x1++;
else
x1--;
if(dy>0)
y1++;
else
y1--;
p+=2*abs(dy)-2*abs(dx);
}
putpixel(x1,y1,col);
}
}
line(x[8],y[8],x[9],y[9]);
}
void main()
{
int gdriver=DETECT,gmode,errorcode;
int i,j,opt;
float **x,**y,**res,fx,fy,dx,dy;
int x1[10]={250,300,300,350,350,350,250,250,250,350};
int y1[10]={50,100,100,50,50,150,50,150,150,150};
int x2,y2;
initgraph(&gdriver,&gmode, "");
clearviewport();
drawimg(x1,y1);
printf("1 - Translation\n2 - Rotation\n3 - Scaling\n");
printf("Enter your choice:");
scanf("%d",&opt);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
x[i][j]=1.0;
else
x[i][j]=0.0;
}
}
if(opt==1) //Translation
{
printf("Enter the x and y factors:");
scanf("%f%f",&fx,&fy);
x[0][2]=fx;
x[1][2]=fy;
}
else if(opt==2) //Rotation
{
Output:
#include<math.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include<dos.h>
#include<math.h>
void drawlin(int,int,int,int);
void drawlin1(int,int,int,int,int,int,float,float,float);
void translate(float[500],float[500],float,float,float,float,float);
void rotate(float[500],float[500],float,float,float);
void scale(float[500],float[500],float,float);
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode,tx,ty;
float x1,y1,x2,y2,t,sx,sy;
initgraph(&gdriver, &gmode, "");
drawlin(100,100,200,100);
drawlin(200,100,200,200);
drawlin(200,200,100,200);
drawlin(100,200,100,100);
drawlin(150,100,100,200);
drawlin(150,100,200,200);
printf("\nEnter the translation vectors");
scanf("%d %d",&tx,&ty);
printf("\nEnter the degree");
scanf("%f",&t);
printf("\nEnter the scaling vectors");
scanf("%f %f",&sx,&sy);
t=t*3.14/180;
drawlin1(100,100,200,100,tx,ty,t,sx,sy);
drawlin1(200,100,200,200,tx,ty,t,sx,sy);
drawlin1(200,200,100,200,tx,ty,t,sx,sy);
drawlin1(100,200,100,100,tx,ty,t,sx,sy);
drawlin1(150,100,100,200,tx,ty,t,sx,sy);
drawlin1(150,100,200,200,tx,ty,t,sx,sy);
getch();
closegraph();
return 0;
}
void drawlin(int x1,int y1,int x2,int y2)
{
float dx,dy,xinc,yinc,steps,x,y,ptx[500],pty[500];
int k,i,j;
float *p;
for(i=0;i<500;i++)
{
ptx[i]=0;
pty[i]=0;
}
printf("\nEnter the end point");
scanf("%f %f" ,&x2,&y2)
dx=x2-x1;
dy=y2-y1;
if(fabs(dx)>=fabs(dy))
steps=fabs(dx);
else
steps=fabs(dy);
xinc=dx/steps;
yinc=dy/steps;
p=(float*)malloc(sizeof(steps));
if(fabs(dx)>=fabs(dy))
p[0]=2*fabs(dy)-fabs(dx);
else
p[0]=2*fabs(dx)-fabs(dy);
x=x1;
y=y1;
putpixel((int)x,(int)y,5);
ptx[0]=x;pty[0]=y;i=1;
for(k=0;k<steps;k++)
{
if(p[k]<0)
{
if(fabs(dx)>=fabs(dy))
{
p[k+1]=p[k]+2*fabs(dy);
x+=xinc;
}
else
{
p[k+1]=p[k]+2*fabs(dx);
y+=yinc;
}
}
else
{
x+=xinc;
y+=yinc;
if(fabs(dx)>=fabs(dy))
p[k+1]=p[k]+2*fabs(dy)-2*fabs(dx);
else
p[k+1]=p[k]+2*fabs(dx)-2*fabs(dy);
}
putpixel((int)x,(int)y,5);
ptx[i]=x;pty[i]=y;
//printf("\n%f %f",ptx[i],pty[i]);
i++;
delay(20);
}
}
void drawlin1(int x1,int y1,int x2,int y2,int tx,int ty,float t,float sx,float sy)
{
float dx,dy,xinc,yinc,steps,x,y,ptx[500],pty[500];
int k,i,j;
float *p;
for(i=0;i<500;i++)
{
ptx[i]=0;
pty[i]=0;
}
printf("\nEnter the end point");
scanf("%f %f" ,&x2,&y2);*/
dx=x2-x1;
dy=y2-y1;
if(fabs(dx)>=fabs(dy))
steps=fabs(dx);
else
steps=fabs(dy);
xinc=dx/steps;
yinc=dy/steps;
p=(float*)malloc(sizeof(steps));
if(fabs(dx)>=fabs(dy))
p[0]=2*fabs(dy)-fabs(dx);
else
p[0]=2*fabs(dx)-fabs(dy);
x=x1;
y=y1;
putpixel((int)x,(int)y,5);
ptx[0]=x;pty[0]=y;i=1;
for(k=0;k<steps;k++)
{
if(p[k]<0)
{
if(fabs(dx)>=fabs(dy))
{
p[k+1]=p[k]+2*fabs(dy);
x+=xinc;
}
else
{
p[k+1]=p[k]+2*fabs(dx);
y+=yinc;
}
}
else
{
x+=xinc;
y+=yinc;
if(fabs(dx)>=fabs(dy))
p[k+1]=p[k]+2*fabs(dy)-2*fabs(dx);
else
p[k+1]=p[k]+2*fabs(dx)-2*fabs(dy);
}
ptx[i]=x;pty[i]=y;
i++;
}
translate(ptx,pty,tx,ty,t,sx,sy);
}
void translate(float ptx[500],float pty[500],float tx,float
scale(ptx,pty,sx,sy);
}
void scale(float ptx[500],float pty[500],float sx,float sy)
{
float c[3][1],i,j,a[3][3],b[3][1],k;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
if(i==j)
a[i][j]=1;
else
a[i][j]=0;
}
a[0][0]=sx;
a[1][1]=sy;
b[2][0]=1;
for(k=0;k<500;k++)
{
b[0][0]=ptx[k];
b[1][0]=pty[k];
for(i=0;i<3;i++)
c[i][0]=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
c[i][0]+=a[i][j]*b[j][0];
}
putpixel((int)c[0][0],(int)c[1][0],5);
}
}
Output:
Translation
x2 = x1 + tx
y2 = y 1 + t y
z2 = z 1 + t y
Scaling
x2 = ax*x1
y2 = ay*y1
z2 = ay*z1
X axis Rotation
y2 = y1 * cos(a) – z1*sin(a)
z2=y1*sin(a)+z1*cos(a)
x2 = x1
Y axis Rotation
z2 = z1 * cos(a) – x1*sin(a)
x2=z1*sin(a)+x*cos(a)
y2 = y1
Z xis Rotation
x2=x1 * cos(a) – y1*sin(a)
y2=x1*sin(a)+y1*cos(a)
z2 = z1
Program 3D Transformations :
#include<iostream.h>
#include<dos.h>
#include<stdio.h>
#include<math.h>
#include<conio.h>
#include<graphics.h>
#include<process.h>
int gd=DETECT,gm;
double x1,x2,y1,y2;
void show_message()
{
char *mess[]={"-","=","["," ","3","D","-","T","r","a","n","s",
"f","o","r","m","a","t","i","o","n"," ","]","=","-"};
int xx=28,xxx=52,i,j;
_setcursortype(_NOCURSOR);
for(i=0,j=24;i<15,j>=12;i++,j--)
{
gotoxy(xx,1);
cout<<mess[i];
xx++;
gotoxy(xxx,1);
cout<<mess[j];
xxx--;
delay(50);
}
_setcursortype(_NORMALCURSOR);
}
void draw_cube(double edge[20][3])
{
initgraph(&gd,&gm,"..\bgi");
int i;
clearviewport();
for(i=0;i<19;i++)
{
x1=edge[i][0]+edge[i][2]*(cos(2.3562));
y1=edge[i][1]-edge[i][2]*(sin(2.3562));
x2=edge[i+1][0]+edge[i+1][2]*(cos(2.3562));
y2=edge[i+1][1]-edge[i+1][2]*(sin(2.3562));
line(x1+320,240-y1,x2+320,240-y2);
}
line(320,240,320,25);
line(320,240,550,240);
line(320,240,150,410);
getch();
closegraph();
}
temp=edge[i][0];
temp1=edge[i][1];
edge[i][0]=temp*cos(theta)-temp1*sin(theta);
edge[i][1]=temp*sin(theta)+temp1*cos(theta);
}
draw_cube(edge);
break;
}
}
void reflect(double edge[20][3])
{
int ch;
int i;
clrscr();
cout<<"-=[ Reflection About ]=-";
cout<<"1:==> X-Axis ";
cout<<"2:==> Y-Axis ";
cout<<"3:==> Z-Axis ";
cout<<" Enter Your Choice :=";
cin>>ch;
switch(ch)
{
case 1:
for(i=0;i<20;i++)
{
edge[i][0]=edge[i][0];
edge[i][1]=-edge[i][1];
edge[i][2]=-edge[i][2];
}
draw_cube(edge);
break;
case 2:
for(i=0;i<20;i++)
{
edge[i][1]=edge[i][1];
edge[i][0]=-edge[i][0];
edge[i][2]=-edge[i][2];
}
draw_cube(edge);
break;
case 3:
for(i=0;i<20;i++)
{
edge[i][2]=edge[i][2];
edge[i][0]=-edge[i][0];
edge[i][1]=-edge[i][1];
}
draw_cube(edge);
break;
}
}
void main()
{
int choice;
double edge[20][3]=
{
100,0,0,
100,100,0,
0,100,0,
0,100,100,
0,0,100,
0,0,0,
100,0,0,
100,0,100,
100,75,100,
75,100,100,
100,100,75,
100,100,0,
100,100,75,
100,75,100,
75,100,100,
0,100,100,
0,100,0,
0,0,0,
0,0,100,
100,0,100
};
while(1)
{
clrscr();
show_message();
cout<<"1:==> Draw Cube ";
cout<<"2:==> Scaling ";
cout<<"3:==>Rotation ";
cout<<"4:==> Reflection ";
cout<<"5:==> Translation ";
cout<<"7:==> Exit ";
cout<<" Enter Your Choice :=";
cin>>choice;
switch(choice)
{
case 1:
draw_cube(edge);
break;
case 2:
scale(edge);
break;
case 3:
rotate(edge);
break;
case 4:
reflect(edge);
break;
case 5:
translate(edge);
break;
case 7:
exit(0);
default:
cout<<"a Press A Valid Key...!!! ";
getch();
break;
}
closegraph();
}
}
Output :
Exercises:
1. Write a program to implement the translation, rotation and scaling on a three
dimensional ball.
The usage of the tool box is explained below. Tool box is used for drawing,
editing and creating special effects in animations.
Pencil Tool:
The Pencil tool is used in much the same way that you would use a real pencil to
draw. Simply select the tool and drag on the stage to draw with the Pencil tool.You can
press the Shift key while dragging to constrain lines to vertical or horizontal directions.
Colors:
You can specify the color with the Stroke Color Tool.
You can apply smoothing or straightening to the lines by setting Pencil mode.
Pencil Modes:
Stroke Panel:
The Brush tool draws brushlike strokes, as if you were painting. It lets you create
special effects, including calligraphic effects. Unlike the Pencil tool, the Brush tool draws
both a fill and an outline. You can press the Shift key while dragging to constrain
drawing to vertical or horizontal directions. You can specify the color with the Stroke and
Fill Color tools.
Brush Modes:
You can specify the Brush Mode in order to define the way the tool works:
• Paint Normal - paints over lines and fills on the same layer.
• Paint Behind - paints in blank areas of the stage on the same layer, leaving lines
and fills unaffected.
• Paint Selection - applies a new fill to the selection when you select a fill in the Fill
modifier or the Fill panel. (This option is the same as simply selecting a filled area
and applying a new fill.)
• Paint Fills - paints fills and empty areas, leaving lines unaffected.
• Paint Inside - paints the fill in which you start a brush stroke and never paints
lines. This works much like a smart coloring book that never allows you to paint
outside the lines. If you start painting in an empty area, the fill doesn't affect any
existing filled areas.
Also, in the Brush options, there is a drop down that lets you select the size of the
brush. Simply click the size you want. Finally, the Brush options let you select the shape
of the brush. Try experimenting with the different shapes and see what effect each offers.
Lock Fill:
The last option listed under Brush options, is the Lock Fill option. When you use
the brush tool in it's default state this option is not turned on. Let's assume that you
selected a gradient fill and painted something using the brush tool. In this case the brush
tool would use the center of your painting as the center for the gradient fill. Now, if you
paint yet another drawing next to the first one, Flash will use the new drawing's center as
center for the gradient fill. However, had you pressed the "Lock Fill" option before
drawing the second painting, Flash will maintain the gradient center from the first
painting. The best way to understand this option is trial and error, so if you don't get the
above explanation, then try painting with and without the "Lock Fill" option set. While
doing so, make sure that you use a gradient fill for the drawing or you won't see any
Line tool:
The Line tool is used in much the same way that you would use a real pencil to
draw with a ruler. Simply select the tool and drag on the stage to draw a straight line
between the start and end points. You can press the Shift key while dragging to constrain
possible angles for the line. By default this will only allow for lines that are either
horizontal, vertical or 45 degrees between. You can specify the color with the Stroke
Color Tool.
Curving:
1. You can turn a straight line into a curve with the Arrow tool
2. Make sure the line is not selected (you can do this by clicking somewhere on an
empty spot on the stage).
4. Click on the line, and while holding down the mouse button, drag the curve.
Moving
You can move a line with the mouse, quite similar to how you'd turn it into a curve or
you can move it with the arrow keys.
The "square" connected to the line where it says "Click this square" is used to set
the origin for coordinates - either at top left or center of the stage. Fields for X and Y are
used to enter the position of the selected object. Fields for W and H are used to enter the
width and height of the selected object.When working with lines, one might think that
height would be 1 for a thin line. However, width and height refers to the square between
the start and end points of the selected object. A horizontal line that is 100 pixels wide
and 1 pixel high spans a square of 100 x 1 pixels. A similar line would span a square of
Oval tool:
The Oval tool is used to make circular objects. Simply select the tool and drag on
the stage to draw a circle that spans between the start and end points. You can press the
Shift key while dragging to ensure your circle is perfectly round. You can specify the
colors with the Stroke and Fill Color Tools.
When you draw a circle, Flash actually creates two objects: the fill and the
outline. This may cause problems if you try to move your circle to a new position,
because if you fail to select both objects, only the one selected will be moved. To avoid
this it's often a good idea to "group" the outline with the fill, thus locking them together
as if it was a single object.
(You can do this in two ways: 1) Select the Arrow tool in the toolbox, and while
holding down the SHIFT key click on both the fill and the outline. 2) Select the Arrow
tool in the toolbox, and drag a rectangle outside your circle)
(If at a later point you want to "break" apart the grouped objects, you can do it by
selecting the grouped object then pressing Ctrl+B).
You can position the oval perfectly using the info panel as in the case of lines.
Erase Tool:
The Erase tool works similar to a classic eraser. Simply select the tool and drag
on the Stage to erase things.
You can double click the Eraser tool to delete everything on the stage. (If you
happen to do this by mistake you can always click Ctrl+Z to undo).
In the options listed at the bottom of the toolbox you can specify the Eraser Mode:
1. Select the Eraser tool and then click the Faucet modifier.
2. Click the stroke segment or filled area that you want to delete.
In the options listed at the bottom of the toolbox there is a drop down that lets you
specify the Eraser shape and size. Use this option to customize the size and look of the
eraser.
There are other ways to delete things besides using the Eraser tool. The most
common way is to select one or more objects and then press the DEL key on the
keyboard. You can delete an entire layer by clicking the layer at the top of your screen
and dragging it to the Trash bin. You can delete several frames at once by selecting the
frames (and layers) in the timeline, then right click and choose "cut frames".The Ink
Bottle tool lets you change the stroke color, line width, and style of lines or shape
outlines. Using the Ink Bottle tool, rather than selecting individual lines and objects,
makes it easier to change the stroke attributes of multiple objects at one time.
2. Choose a stroke color as described in Using the Stroke and Fill controls in the toolbox.
3. Choose line style and line width from the Stroke panel.
You can use the stroke tool to apply outlines even for things that were initially
made without outlines. For example, if you initially created a rectangle with no outline,
and then later decided for an outline, simply use the Ink Bottle tool as described above
The Paint Bucket tool fills enclosed areas with color. It can both fill empty areas
and change the color of already painted areas. You can paint with solid colors, gradient
fills, and bitmap fills. You can also use the Paint Bucket tool to adjust the size, direction,
and center of gradient and bitmap fills.
3. Click the Gap Size modifier and choose a gap size option:
• Don't Close Gaps : if you want to close gaps manually before filling the shape.
Closing gaps manually can be faster for complex drawings.
• Choose one of the Close options to have Flash fill a shape that has gaps.
Depending on the type of object you're painting you will see different handles:
b. To change the width of the fill, drag the square handle on the side of the bounding
box. (This option resizes only the fill, not the object containing the fill.)
c. To change the height of the fill, drag the square handle at the bottom of the bounding
box.
d. To rotate the fill, drag the circular rotation handle at the corner. You can also drag the
lowest handle on the bounding circle of a circular gradient or fill.
e. To scale a linear gradient, drag the square handle at the center of the bounding box.
f. To change the radius of a circular gradient, drag the middle circular handle on the
bounding circle.
g. To skew or slant a fill within a shape, drag one of the circular handles on the top or
right side of the bounding box.
Note: To see all of the handles when working with large fills or fills close to the edge of
the Stage, choose View > Work Area
Eyedropper tool:
You can use the Eye Dropper tool to copy fill and stroke attributes from objects.
1. Select the Eye Dropper tool and click the object whose attributes you want to copy.
(When you click a stroke, the tool automatically changes to the Ink Bottle tool. When
you click a filled area, the tool automatically changes to the Paint Bucket tool)
2. Click the object that you want to apply the new attributes to.
Rather than painting with a fixed color or gradient you can paint using a bitmap
image. A very important special use of the eyedropper tool is to select bitmap fills.
Place a bitmap image on the stage. Either drag it from your symbol library
(Ctrl+L or Window > Library) or import a bitmap image from a file (Ctrl+R or File >
Import).
Make sure the imported bitmap is selected. (If not: click on it with the Arrow
tool).
Select the Eye Dropper tool and click on the image. You will now see a miniature
of your image in the Color Fill tool box. Use the Paint Bucket tool to apply the bitmap fill
to an object. (Note: you can apply the fill to any filled object as well as any closed
outlined area.)
Pen tool:
The purpose of the Pen tool is to allow you to draw precise paths as straight lines
or smooth, flowing curves. You can create straight or curved line segments and adjust the
angle and length of straight segments and the slope of curved segments afterwards. There
are two methods for drawing with the Pen tool:
2. Click on the stage to set points, and watch how Flash automatically connects points as
you set them.
3. To complete the path leaving it as either an open or closed shape. Do one of the
following:
3a. To complete an open path, double click the last point or click the Pen tool in the
toolbox, or Control-click (Windows) or Command-click (Macintosh) anywhere away
from the path.
3b. To close a path, position the Pen tool over the first anchor point. A small circle
appears next to the pen tip when it is positioned correctly. Click to close the path, and
watch how Flash automatic adds a fill once the path becomes a closed outline.
1. Select the pen tool and click twice to create a straight line - on the second click
keep the mouse button down.
2. Drag the mouse towards yourself - which will cause the control line to appear.
The control line is pulled in one end and has a drag point in the other end.
3. Move the mouse from side to side (B) and forward and down (A)- still holding
down the button, and see how the drag point moves accordingly. The drag point
defines both how much and in which direction the initial straight line is dragged.
4. When the curve on the initial straight line is shaped the way you want it release
the mouse button, and the end result appears while the control line disappears.
• Select the first frame. Import your image onto stage, upon which you would
want to implement motion tween.
File>Import>Import to Stage, or just press (Ctrl+R).
Or you can even draw your own object, you can either choose Rectangular tool
or Oval tool from the tool box and draw your desired shape.
• Now select your object on the stage and press F8 to convert this image to a
Symbol. Convert to Symbol window will pop-up. Name your Symbol.
• Note: You can create motion tween only on symbols. So any object upon
which you would want to implement motion tween, has to be converted to a
Symbol.
• Right now your Symbol is in frame1 of Layer1. Select frame 20 and press F6
to insert a new keyframe.
• Still keeping playhead on frame 20, move your Symbol to any other position
other than the present one.
• Select any frame between, 2 to 19 and select Motion from the tween pop-up
menu in the Property inspector. Now your Layer will look something like the
one shown below.
Shape Tween:
• Select the first frame. Now go to your working area and draw any object.
To start off with, may be you can draw a circle.This is going to be your
initial object.
• Select frame 20 and press F6 to insert a new keyframe.
• Still keeping playhead on frame 20, delete the object present in your
working area. Now draw a different object, may be a square.
• Select any frame between, 2 to 19 and select Shape from the tween pop-up
menu in the Property inspector. Now your Layer will look something like
the one shown below.
7.3 Key Frame, Guide Layer, Masking and Onion Skin Techniques
Key Frame:
The Key Frame is the foundation of any flash movie. It marks where an event occurs for
example, the appearance of a symbol or the end of a motion-tween.
In order to create a Key Frame, select the relevant frame and choose Insert> Insert
Keyframe or right click your mouse on the frame for the same menu. Once you've
inserted the key frame a hollow dot will appearing the frame. You can also left click the
frame and press the F6 key.
This creates a key frame. Then you can draw or create symbols in the key frame location.
Motion Guide:
Motion Guide is nothing but moving your symbol in a predefined path such as curves or
circles. Learn how to move Flash objects in circular, zig zag or curved paths using Flash
motion guide.
2. Right click on the "graphic" label and select "Add Motion Guide" from the
pop-up window.
3. A new layer will appear on top of the "graphic" layer with the label
"Guide:graphic" along with the guide icon.
4. Draw the path for your symbol in this new layer using pencil or line tool.
For example: I drew a circle for my car.
6. Now go to "Frame 1" of "graphic" layer and drag your symbol to one end of
your path. While dragging, you will see a bubble on the symbol. That bubble
should go right below the path. Something like the one shown below.
8. Now drag your symbol to other end of your path. Again, the bubble should go
right below the path.
9. Select any frame between 1 to 50 of your "graphic" layer. Right click and
select "motion tween" from the pop-up menu.
Masking :
Import (Ctrl + R) any color photo to be masked and its black & white version onto the
stage.
1) Now add a new Layer and move the Color picture into it. Make sure both pictures are
perfectly on top of each other.
2) Add a new Layer above the color picture layer and name it as 'Image Mask'.
3) Draw any vector, say a rectangle with a height more than the picture height and width
say 100. Convert the vector to a graphic symbol (select and press F8).
4) Right-click the Layer named 'Image Mask' and select Mask from the pop-up menu.
This command will make the current 'Image Mask' layer to mask the layer below it
(containing the color photo), resulting in the color photo being shown only the area
specified by the mask layer.
5) Save your work and test the Movie (Ctrl + Enter). The movie will look as shown
above.
• Open Flash. Click on File/New. Chose the Templates tab. Select Photo Slideshows.
Click on OK. You will see a ready-made Flash photo slideshow created. Press
Cntrl+Enter to view the file. Press the auto play button to view the slideshow.
• To replace the images with your own, select the bottom layer called picture layer and
click on the trash can icon to delete it.
• Create a new layer by clicking the Insert Layer button, and name this new layer My
Photos. Make sure that this new layer is the bottom layer.
• Select the first blank keyframe in the My Photos layer, select File > Import >
Import to Stage, and locate your photo sequence. Select the first image in the series,
click Add, and click Import. Flash recognizes that your image is part of a series and
asks you to import all files in the series. Click Yes to complete the import process.
Flash places each image on separate keyframes. You can move the images so they are
centered in the stage or you can choose the images on the stage and make the X and Y
coordinates 0 so they are centered in the stage.
• Your images appear in the Library panel and can be replaced later if needed by
double clicking on the image in the laibrary window and clicking on the import
button tos elect the new image file.
• You can safely delete the old images that were included in this document from the
library if you wish, they are saved in the photos folder.
• If you have more than four images, make sure that all the other layers have an equal
number of frames. Select the frame and click on F5 to add new frames.
• Change the captions for the images, by replacing the text in the Captions layer and
adding new keyframes with text for the new images. You do not have to worry about
the photo number field. The template automatically determines how many images are
in your document and indicates which photo you are currently using.
• Change the title in the Title, Date layer.
Press Ctrl+Enter to view the completed Flash Photo Slidshow. The Photo
Slideshow template also has a built-in autoplay mode that automatically changes
the photo after a set delay. The template is set to a default delay time of 4 seconds, but
you can change this setting easily.
• Select the delay and change this value to a new delay value in seconds.
• Save and publish your document.
To apply a gradient to text in Flash you need to use the Break Apart Command.
First, type out some text in Flash using the text tool.
Choose the text and click on Modify > Break Apart. The text will will look like the
image shown below.
The text is still not as an editable vector object, so choose the text again and click on
Modify > Break Apart again. The text will will look like the image shown below.
Now, to this text you can apply a gradient fill. Choose the text and in the color mixer
panel, choose Linear Fill and choose your gradient colors. By default the gradient will be
applied to each letter separately, if you need to apply it to the entire word, select the paint
bucket tool and drag it over the text so the gradient fills the entire word.
After the application of gradient the final text looks as shown below.
Onion Skinning:
Onion skinning enables you to view multiple frames at the same time. It is especially
helpful when creating an animation consisting of a series of keyframes. Onion Skin icons
are found below the time line. The first allows you to view frames in color while the
other displays the object as outlines (keyframes are however displayed in color).
tool . Once traced, the vector drawing can be embellished using other features in
Flash.
When imported into a new Flash movie (File - Import), the image shown above is
centered on the page. Next add a Blank Keyframe on the second frame and click on the
Onion Skin marker. A faded view of the original image is seen.
Still in the second frame, choose the pencil tool with 1 pixel thick line and start tracing
the image manually. Use the zoom tool. The result is an outline of the photograph. Then
delete the original photograph from the first frame as well as its symbol from the library.
Then fill up some areas of the outlined drawing and save it as a symbol. There are two
examples shown below. You can have your own design and make it a symbol.
Exercises:
This is the Marquee tool. The tool consists of a number of different ways of
making selections. By selection you can select a part of an image and do something with
it, like a filter, a color adjustment, etc,. There are four different types of Marquee tool.
The first is the Rectangular Marquee Tool. This allows you to make rectangular
selections. The same follows with the Elliptical Marquee Tool, it selects a circular area.
The way you use this tool is click and hold down the mouse and drag.
This is the Move Tool, this is the tool you use to move objects around in
Photoshop. It is the most commonly used tool. You can use it by clicking and dragging
items on the canvas.
This is the Lasso tool. There are three different types of Lasso Tool. The regular
Lasso Tool allows you to make a selection by dragging and drawing a shape with the
mouse. The polygonal Lasso Tool allows you to click and then move your mouse and
then click again at a different point, which you can do to create any kind of polygonal
shape (a closed object with straight sides). The Magnetic Lasso Tool is special, you start
out by clicking it once and then drag your mouse in any direction, the Magnetic Lasso
Tool will follow the edges of an image (Where to different colors are contrasted) without
you having to do anything.
This is the Magic Wand. The magic wand allows you to click in different areas of
an image and select related colors to where you clicked. For example if you had an image
of a person against a white background, you could click the white background and it
would select the area around the person.
This is the crop tool. This tool allows you to crop or cut the image to a different
size. You can also use it to make the image larger. Click and drag the mouse to select a
crop area. You can adjust it by dragging the handles (The little square boxes on the
corners and sides that allow you to change its size).
This is the slice tool. A slice is a piece of an image. You would use this tool when
you want to save the image as different pieces. It is normally used when designing web
pages. To use the slice tool all you have to do is drag around an area of the canvas. The
area you drag around is now a slice. You can later export these slices as individual
images.
The slice select tool allows you to edit existing slices, to use this tool you just
click on the slice and resize it by dragging the handles that show up.
These are the healing tools. The first one is called the "Spot Healing Brush Tool"
it allows you to clean up imperfections or blemishes in an area of color. Let's say you
have a person and they have a red spot on their face or a zit, then you could click on the
zit with the spot healing brush and make it disappear. Make sure that the brush is
somewhat larger than the blemish its self. The healing brush tool is the same as the spot
healing brush tool in that it allows you to clean up a blemish or an imperfection, the only
difference is that you have to select an area of the image you want it to use to replace the
blemish. For example if you wanted to remove a spot on a car, you would go to an area of
the car that is nice and "alt/option+click" the area, you could then click on the blemish
and it should disappear.
The patch tool allows you to cover up larger parts of the image than the healing
brushes. All you have to do is to make a selection with any selection tool -- or the patch
tool (You would select the area you want to be replaced), then you would select the patch
tool and drag the selection to a part of the image you would want to use to replace the old
part of the image. When you let go, the area that was selected will be blended with the
area you dragged the selection to. If you are cloning out a large part of an image, you
don't want to just use this tool. The red eye tool is for removing red eye. You just click it
on the part of the eye that is red and the red eye will be handled, if you need to you might
need to adjust the pupil size to get best results.
These are the painting tools they allow you to add color to an image like you are
using a brush or a pencil.The Brush tool has been in Photoshop for a long time. You use
it by dragging it across the image. The pencil tool is for drawing lines. It is mainly used
for drawing rough lines, as apposed to the brush which draws smooth edges. The color
replacement tool is a very useful tool for image correction. You use it like a regular
brush, but it allows you to change the colors of the area you are painting. There are many
settings for this tool which allow you to efficiently change the color of a specific part of
an image without ruing the image itself.
These are the clone tools.These tools are best used in conjunction with the patch
tool to create realistic effects from artificially removed parts of an image.The clone stamp
tool allows you to take a part of an image and paint it into a different part. Hold down
Alt/Option and click on the area of the image you want to use to paint with. Then start
painting in the area you want to remove. By selecting "aligned" in the tool settings bar
allows your set part of the image to copy from change as you paint. The pattern stamp
tool allows you to paint an image by using a pattern. You just select a pattern to use and
start painting.
These are the history brush tools. They allow you to paint back to some time in
the images history. These tools can be very useful at times. To use the history brush tool
select the part of the history you want to paint back to. (You do this by clicking the
history brush icon to the left of the history state) and then start painting, the same image
from history will be painted from the point that is selected. The art history brush does the
same thing as the history brush except, you can set paint like options, so that when you
paint back the history, it looks like it was painted or whatever visual effect you choose.
These are the eraser tools, they allow you to remove parts of an image. The most
useful tool out of these is the regular eraser. To use the eraser tool, just select a brush and
start dragging around the area of the image wanted to be erased. The Background Eraser
tool allows you to erase an area of color that is in the middle of the brush area without
erasing parts that are not similar to the color in the middle of the brush. This may be
confusing, here is an example: You have a soccer ball on grass and you want to cut the
soccer ball out with the background eraser tool. So, you take the background eraser and
start to drag around the edges of the ball, ensuring that the center of the brush is in the
green grass part. This will erase the grass and leave the soccer ball untouched. The magic
eraser tool is like the magic wand, but instead of creating a selection, it erases.
These are fill tools. Used for filling areas of an image with color. The gradient
tool allows you to drag over an area of an image and create a gradient. You use the
gradient maker tool to create the gradient and then you click and drag on the image to
create the gradient. The Paint Bucket Tool is like the magic wand, but instead of selecting
the image, it paints the image (Adds color)
Open an image in Photoshop. Save it as a psd file. In the Layers palette, double click
on the background layer (the only layer), and, in the dialog box that appears, name the
layer “First”. Only in Photoshop v. 6.0, the background layer can be renamed by double
clicking. To rename any other layer, you must press Alt while double clicking the layer’s
current name. Background layers do not allow transparency, and cannot have layer
effects added to them. Renaming the background layer turns it into a regular layer. Layer
styles are easy to use shortcuts and a easy way to create effects, but they have limitations.
To apply a style to a layer using style palette just click, drag, and drop that style on your
object. You can drag and drop your style on any object on any layer, not just the current
layer. You have partially created a graphic using layerstyles and want to enhance it using
other photoshop tools then you will have to rasterize the layer styles. Photoshop dosent
have an obvious 'one button press' way to do this, fortuantely it’s very easy to do
manually.
Now the layer will behave just as if you drew everything on using a paintbrush, and
you will be able to apply filters, and adjust levels all you want.
1. Create a new document and call it whatever you want. Set the dimensions to the
656px wide, and 265px height. Make sure the Background type is set to “white.”
2. Create some text that preferably doesn’t have a descender below the baseline like
“MacBook Pro.”
3. Duplicate the “MacBook Pro” layer and rename the bottom layer to “shadow” + hide
the top text later to look only at the shadow layer.
4. In order to make this look like a shadow, add a blur to the text. FIRST: Have the
“shadow” layer selected and go in the menu go to LAYER > RASTERIZE… >
TYPE. After this, go to FILTER > BLUR > GAUSSIAN BLUR… and set the Radius
to 4.0 pixels. This will make it soft enough to replicate a shadow. You will have
something like this:
5. Now reveal the “MacBook Pro” layer so that it overlaps the shadow layer. With the
“shadow” layer still selected, go to EDIT > TRANSFORM > SCALE. Now drag
down and shrink from the top edge so you get something like this:
6. Nudge the shadow layer up by a few pixel to make it fit on the base of the MacBook
Pro text, like this:
7. Now, on the shadow layer, we must add a layer mask by hitting the “vector mask”
button like this:
8. Now, grab the Gradient tool (shortcut key: G) with the default colors going from
black to white. Point your cursor on the top edge of the shadow, and slightly drag
DOWNWARD. You should get a fading effect where the top is faded away. You
might have to try this a few times until you get it right. You should have something
like this:
9. Now duplicate the MacBook Pro layer and rename the copy to “reflection.” Now flip
the text vertically: EDIT > TRANSFORM > FLIP VERTICAL. Now select the Move
Tool (shortcut key: V) and use the arrow keys on your keyboard to nudge it below the
MacBook Pro text. Set the Opacity of this layer to 20%. Your layers panel should
look like this:
And your artwork should look like the image shown below.
10. Now add a layer mask to this layer just like we did in step 7. With the same Gradient
Tool settings, this time drag UPWARD from the bottom of the layer to fade away the
bottom edge. After a few tries, you should have something like this:
• filter > blur > radial blur then use these settings:
• duplicate this layer and set the blening mode to linear burn add some brushing and
this is the final effect will look like as shown below:
One your image is open, create a new layer(Shift+Ctrl+N) and name it droplets and fill it
with black using the paint bucket tool(G).
Now the fun part starts, select Filter => Render => Fibres and use the settings below.
Select Filter => Texture => Stained Glass and apply the settings below.
Just one more filter needs to be applied, use the settings below.
Now select the Magic Wand Tool(W) and make sure the foreground is black, tolerance is
set at 32 and contiguous is checked. Once selected, click on the black area on the droplets
layer. This will select all the black and leave the droplets. Now delete the selected by
pressing the delete key on you keyboard.
Deselect by pressing Ctrl+D and set the droplets layer to overlay and the opacity to 75%,
you figure will look as shown below:
The last thing we do is add a Layer Mask and select the Brush Tool again, make sure the
foreground is black. With the appropriate brush size, erase the unwanted droplets.
2. Next put each picture on its own layer putting the picture you want blending on the top.
Then using the rectangle marquee tool on the top layer, make a rectangle selection of
what you want blended.
3. Now go to SELECTION>FEATHER. A box will pop up. This will determine how
much the pictures will blend together. Give 30.
4. Now make sure the rectangle that you made in the beginning is still there. And hit Clrl
+ C (copy). This will copy the top image. Now click Clrl + V (paste) this will paste the
top picture into the feathered rectangle.
Start by using the Text Tool and typing the main word of your company name. Select
a darkish or midtone colour, and choose a serif (curly-edged) font such as Palatino
Linotype or Times New Roman. Use all capitals, and slightly enlarge the first letter.
Using the same font, put the rest of your company name, or some other descriptive phrase,
underneath the main header. Use a much smaller font size, and increase the letter spacing
by typing a high number into the "Tracking" box. (Alternatively, you can just put a space
between each letter.)
The horizontal lines can be put to separate out and highlight the text of the company logo.
An easy way to make a line is to use the text tool and type an underscore ( _ ), then press
Ctrl+T to transform it into an elongated shape.
With just words and lines, the logo design will look dull. Use the Shape Tool in Adobe
Photoshop to draw a shape. Another option is to use the Text Tool, and type a character
in the Wingdings font.
At this point, your company logo design is finished, and will look good both on
screen and on paper. Embellishing your company logo design will make it look nicer, but
it won't be as clear.
A black border will help accentuate the colours in your logo design. With your
background colour set to black, click Image > Canvas Size, and increase the height of the
image a bit. The extra space on your logo design will be filled with the background
colour (black).
Choose a very light grey colour, select the Text Tool, and write "jk" in Wingdings font.
Make the font size very large. "j" and "k" in Wingdings show up as nice swirly characters,
which make a nice watermark. In the Layers window, drag this layer almost to the bottom
of the list, so it doesn't cover up any other layers.
To add some effects, right-click on a layer, then click "Blending Options" and add the
following effects to some of the layers: Bevel and Emboss (set to Inner Bevel), Drop
Shadow, Gradient Overlay (set to Overlay mode.)
Also change the Comco header's text colour to blue, and make the horizontal lines orange.
Feel free to change any of the colours on your company logo to whatever suits your
purpose.
You can use the magic wand and eraser to cut out any image in Photoshop. It willl be
useful, especially when the background of the image consists of only one or two colors.
Copy the apple layer you just opened by dragging the background layer to the 'New layer
icon' in your layer palette.
Change the name of the Background copy layer to ‘apple' by double clicking the Layer
and hide the background image by clicking on the eye in front of the layer. Your layers
palette should now look like this.
Select the magic wand tool and the settings in the toolbar as followed:
select 'Anti- aliased' for softening the edges of the selection we make select 'Contiguous'
so bordering areas using the same colors also get selected. Otherwise, all pixels using the
same colors will be selected.
(For Tolerance: Enter a low value to select only the colors very similar to the pixel you
click, or enter a higher value to select a broader range of colors)
Click in the right or left top corner of the image. All white in the background is now
selected.
Press delete to delete the white and then press Ctrl-D to delete the selection.
Select the lighter parts of the shadow on the left and right in one selection. To add to the
selection hold down the Shift button, to subtract from the selection hold down the Alt
button.
Delete the selection and press Ctrl D to deselect. This last piece of shadow is the most
difficult to select with the Magic Wand Tool. Hold the Shift key down while making the
selection to add to the one.
Press delete and Ctrl D again and create a new layer by pressing the 'New layer icon' in
your Layers palette. Drag this new layer between the Background layer and the Apple
layer and fill it with black using the Paint Bucket Tool. Your Layer palette should now
look like this.
Add the black behind the apple layer for the contrast, so you can see where all the white
areas are that you need to remove manually with the Eraser Tool
Select the Eraser Tool set mode to Brush and set Brush size to 40 pixels. Set Opacity to
100% and Flow also to 100%.
Erase the larger part of the white areas. To remove the thin white circle that is around the
apple zoom in to 200% and set the brush size to 10 pixels. You also soften the edges of
the apple by deleting the white edges around the apple with the Eraser Tool set in Brush
mode. When you're finished you should have a clear cut out of the apple as shown
below.
Exercises:
a. Convert the given old photo into a new photo using a photo editing tool.
Appendix
Example Program 1:
A small program that displays an animated circle on the screen with an animated
background
#include "graphics.h"
#include "conio.h"
#include "stdlib.h"
void main()
{
int gd,gm;
gd=DETECT;
setfillstyle(1, 14);
bar(100, 100, 540, 380);
while(!kbhit())
{
putpixel(random(439)+101, random(279)+101,random(16));
setcolor(random(16));
circle(320,240,random(100));
}
getch();
closegraph();
}
Output:
Example Program 2:
A program that draws a bar chart and pie chart for the values given by the user using
pattern fill option
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
void drawbarchart(float a[],int n,int scale)
{
int i;
char titl[20];
float barwidth=getmaxx()/n;
for(i=0;i<n;i++)
{
if(i!=0) setfillstyle(i,i);
else setfillstyle(SOLID_FILL,getmaxcolor());
bar(i*barwidth,getmaxy()-
((float)a[i]/scale)*getmaxy(),(i+0.9)*barwidth,getmaxy());
bar(0,i*13,20,i*13+10);
itoa(i,titl,10);
outtextxy(22,i*13+2,titl);
}
}
void drawpiechart(float a[],int n,int radius)
{
int i;
float tot=0;
float barwidth=getmaxx()/n;
int stangle=0;
char titl[20];
for(i=0;i<n;i++) tot+=a[i];
for(i=0;i<n;i++)
{
if(i!=0) setfillstyle(i,i);
else setfillstyle(SOLID_FILL,getmaxcolor());
pieslice(getmaxx()/2,getmaxy()/2,stangle,stangle+a[i]/tot*360,radius);
stangle=stangle+a[i]/tot*360;
bar(0,i*13,20,i*13+10);
itoa(i,titl,10);
outtextxy(22,i*13+2,titl);
}
}
int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int i,n,radius,scale;
float gra[5000];
clrscr();
printf("Enter no. of values:");
scanf("%d",&n);
printf("Enter values:\n");
for(i=0;i<n;i++) scanf("%f",&gra[i]);
printf("Enter scale for barchart:");
scanf("%d",&scale);
printf("Enter radius for piechart:");
scanf("%d",&radius);
/* 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 */
}
drawbarchart(gra,n,scale);
getch();
cleardevice();
drawpiechart(gra,n,radius);
getch();
closegraph();
return 0;
}
Output:
Example Program 3:
Text Clipping
Algorithm:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
int xmin=50,ymin=100,ymax=350,xmax=350;
int xpos[7]={100,200,340,400,150,40,30};
int ypos[7]={98,250,193,220,549,129,348};
char s[4]="TEXT";
void textclip1()
{
int i=0,j=0;
for(i=0;i<getmaxx();i++)
{
for(j=0;j<getmaxy();j++)
{
if(getpixel(i,j)==15)
{
if((i<=xmax)&&(i>=xmin)&&(j<=ymax)&&(j>=ymin))
putpixel(i,j,15);
else
putpixel(i,j,0);
}
}
}
}
void textclip2()
{
int i=0;
clearviewport();
for(i=0;i<7;i++)
{
if(xpos[i]<xmin || ypos[i]<ymin || (ypos[i]+textheight(s))>ymax ||
(xpos[i]+textwidth(s))>xmax);
else
outtextxy(xpos[i],ypos[i],s);
}
}
void textclip3()
{
int i=0,j=0,sx;
char *str;
clearviewport();
rectangle(xmin,ymin,xmax,ymax);
for(i=0;i<7;i++)
{
for(j=0;j<4;j++)
{
sx=j*textwidth(s)/4;
str[0]=s[j];
str[1]='\0';
if((sx+xpos[i])<xmin || ypos[i]<ymin ||
(sx+xpos[i]+textwidth(s)/4)>xmax || (ypos[i]+textheight(s))>ymax);
else
outtextxy(sx+xpos[i],ypos[i],str);
sx=textwidth(str);
}
}
}
void main()
{
int gdriver=DETECT,gmode,errorcode;
int i,opt;
initgraph(&gdriver,&gmode, "");
clearviewport();
printf("Before clipping:");
rectangle(xmin,ymin,xmax,ymax);
settextstyle(6,0,7);
for(i=0;i<7;i++)
{
outtextxy(xpos[i],ypos[i],s);
}
printf("\n1. Pixel clipping\n2. All or none string clipping\n3. All or none character
clipping\n");
scanf("%d",&opt);
printf("After clipping:");
switch(opt)
{
case 1:
textclip1();
break;
case 2:
textclip2();
break;
case 3:
textclip3();
break;
}
rectangle(xmin,ymin,xmax,ymax);
getch();
closegraph();
}
Output:
Example Program 4:
Program Shear:
#include <graphics.h>
#include <dos.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define ROUND(a) ((int) ((a)+0.5))
struct matrix
{
float arr[3][3];
};
struct matrix currmat;
struct matrix tmp1;
struct matrix tmp2;
void setNone()
{
currmat.arr[0][0]=1;
currmat.arr[0][1]=0;
currmat.arr[0][2]=0;
currmat.arr[1][0]=0;
currmat.arr[1][1]=1;
currmat.arr[1][2]=0;
currmat.arr[2][0]=0;
currmat.arr[2][1]=0;
currmat.arr[2][2]=1;
}
void mulMat()
{
int i,j,k;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
tmp2.arr[i][j]=currmat.arr[i][j];
currmat.arr[i][j]=0;
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
currmat.arr[i][j]= (tmp1.arr[i][k]*tmp2.arr[k][j])+currmat.arr[i][j];
}
}
}
void setScale(int x,int y)
{
tmp1.arr[0][0]=x;
tmp1.arr[0][1]=0;
tmp1.arr[0][2]=0;
tmp1.arr[1][0]=0;
tmp1.arr[1][1]=y;
tmp1.arr[1][2]=0;
tmp1.arr[2][0]=0;
tmp1.arr[2][1]=0;
tmp1.arr[2][2]=1;
mulMat();
}
void setRot(float x)
{
tmp1.arr[0][0]=cos(x);
tmp1.arr[0][1]=-sin(x);
tmp1.arr[0][2]=0;
tmp1.arr[1][0]=sin(x);
tmp1.arr[1][1]=cos(x);
tmp1.arr[1][2]=0;
tmp1.arr[2][0]=0;
tmp1.arr[2][1]=0;
tmp1.arr[2][2]=1;
mulMat();
}
tmp1.arr[0][2]=-shx*yref;
tmp1.arr[1][0]=0;
tmp1.arr[1][1]=1;
tmp1.arr[1][2]=0;
tmp1.arr[2][0]=0;
tmp1.arr[2][1]=0;
tmp1.arr[2][2]=1;
mulMat();
}
void setShearY(int shy,int xref)
{
tmp1.arr[0][0]=1;
tmp1.arr[0][1]=0;
tmp1.arr[0][2]=0;
tmp1.arr[1][0]=shy;
tmp1.arr[1][1]=1;
tmp1.arr[1][2]=-shy*xref;
tmp1.arr[2][0]=0;
tmp1.arr[2][1]=0;
tmp1.arr[2][2]=1;
mulMat();
}
void putpixel1(int x,int y,int c)
{
float inx,iny;
inx = currmat.arr[0][0]*x + currmat.arr[0][1]*y
+ currmat.arr[0][2];
iny = currmat.arr[1][0]*x + currmat.arr[1][1]*y +
currmat.arr[1][2];
putpixel(300+inx,240+iny,c);
}
void setXRef()
{
tmp1.arr[0][0]=1;
tmp1.arr[0][1]=0;
tmp1.arr[0][2]=0;
tmp1.arr[1][0]=0;
tmp1.arr[1][1]=-1;
tmp1.arr[1][2]=0;
tmp1.arr[2][0]=0;
tmp1.arr[2][1]=0;
tmp1.arr[2][2]=1;
mulMat();
}
void setYRef()
{
tmp1.arr[0][0]=-1;
tmp1.arr[0][1]=0;
tmp1.arr[0][2]=0;
tmp1.arr[1][0]=0;
tmp1.arr[1][1]=1;
tmp1.arr[1][2]=0;
tmp1.arr[2][0]=0;
tmp1.arr[2][1]=0;
tmp1.arr[2][2]=1;
mulMat();
}
int ids_st;
int dl_st;
int t_st;
int st;
int st_f;// 0 - drawing , 1 - skipping
void setPlotVals(int ids,int dl, int t)
{
st=0;
ids_st=ids;
dl_st=dl;
t_st=t;
st_f=0;
}
void circle1 (int xCenter, int yCenter, int radius,int c,int
obey_attr,int fill);
void plot(int x,int y,int c,int obey_attr)
{
if(!obey_attr)
{
putpixel1(x,y,c);
return;
}
if(st_f==0)
{
st++;
if(st==dl_st)
{
st_f=1;
st=0;
}
if(t_st>1) circle1(x,y,t_st/2,c,0,1);
else putpixel1(x,y,c);
}
else
{
st++;
if(st==ids_st)
{
st_f=0;
st=0;
}
}
}
void line1(int xa, int ya, int xb, int yb,int c,int obey_attr)
{
int dx = xb - xa, dy = yb - ya, steps, k;
float xIncrement, yIncrement, x = xa, y = ya;
if (abs (dx) > abs (dy)) steps = abs (dx) ;
else steps = abs(dy);
if(steps ==0) return;
xIncrement = dx / (float) steps;
yIncrement = dy / (float) steps;
plot (ROUND(x), ROUND(y),c,obey_attr);
for (k=0; k<steps; k++)
{
x += xIncrement;
y += yIncrement;
plot (ROUND(x),
ROUND(y),c,obey_attr);
// putpixel1(ROUND(x),ROUND(y),c);
}
}
void ellipsePlotPoints (int xCenter, int yCenter, int x, int
line1(xCenter-x,yCenter+y,xCenter+x,yCenter+y,c,0);
line1(xCenter-x,yCenter-y,xCenter+x,yCenter-y,c,0);
}
}
void circlePlotPoints (int xCenter, int yCenter, int x, int y,int
y,c,obey_attr,fill);
while (x < y)
{
x++;
if (p<0)
p=p+2*x+1;
else
{
y--;
p+= 2*(x-y) + 1;
}
circlePlotPoints (xCenter, yCenter, x, y,c,obey_attr,fill);
}
}
void ellipse1(int xCenter, int yCenter, int Rx, int Ry,int c,int obey_attr,int fill)
{
float Rx2 = Rx*Rx;
float Ry2 = Ry*Ry;
float twoRx2 = 2*Rx2;
float twoRy2 = 2*Ry2;
float p;
float x = 0;
float y = Ry;
float px = 0;
float py = twoRx2 * y;
ellipsePlotPoints (xCenter, yCenter, x, y,c,obey_attr,fill);
/* Region 1 */
p=(int)(((Ry2 - (Rx2 * Ry) + (0.25 * Rx2))));
while (px < py)
{
x++;
px += twoRy2;
if (p < 0)
p += Ry2 + px;
else
{
y--;
py -= twoRx2;
p += Ry2 + px - py;
}
ellipsePlotPoints (xCenter, yCenter, x, y,c,obey_attr,fill);
}
/* Region 2 */
p = (int)(((Ry2*(x+0.5)*(x+0.5)+ Rx2*(y-1)*(y-1)-Rx2*Ry2)));
while (y > 0 )
{
y--;
py -= twoRx2;
if (p >= 0)
p += Rx2 - py;
else
{
x++;
px += twoRy2;
p += Rx2 - py + px;
}
ellipsePlotPoints (xCenter, yCenter, x, y,c,obey_attr,fill);
}
}
int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int i,n,radius,scale;
float gra[5000];
clrscr();
initgraph(&gdriver, &gmode, "");
errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
setPlotVals(0,0, 1);
setNone();
line1(-1000,0,1000,0,2,1);
line1(0,-1000,0,1000,2,1);
setShearX(2,-20);
line1(0,0,0,50,3,1);
line1(0,50,50,50,3,1);
line1(50,50,50,0,3,1);
line1(50,0,0,0,3,1);
setNone();
setRot(0.4);
ellipse1(100,100,100,50,1,1,0);
setYRef();
ellipse1(100,100,100,50,1,1,0);
setYRef();
setXRef();
ellipse1(100,100,100,50,1,1,0);
setYRef();
ellipse1(100,100,100,50,1,1,1);
setYRef();
setXRef();
getch();
return 0;
}
Output: