Search This Blog

C Program for Shear Transformation - Shear Transformation in 2D Computer Graphics

Shear transformation or shearing is one of the 2d transformations in computer graphics. Here i present a c program for shear transformation of polygons. The shear transformation works as follows:

For shearing along X axis, shearfactor* (y coordinate) is added with x co-ordinates of all points. That is:
newx=oldx+shearfactor*oldy

Similarly, to shear along Y axis, we add shearfactor* (x coordinate) to y co-ordinates of all points.
newy=oldy+shearfactor*oldx

#include<stdio.h>
#include<graphics.h>
#include<math.h>
int graDriver=DETECT,graMode;
int n,xs[100],ys[100],i;
float shearXfactor,shearYfactor;

void DrawFn()
{
for(i=0;i<n;i++)
 line(xs[i],ys[i],xs[(i+1)%n],ys[(i+1)%n]);
}

void shearAlongX()
{
for(i=0;i<n;i++)
 xs[i]=xs[i]+shearXfactor*ys[i];
}

void shearAlongY()
{
for(i=0;i<n;i++)
 ys[i]=ys[i]+shearYfactor*xs[i];
}

void main()
{
printf("Enter number of sides: ");
scanf("%d",&n);
printf("Enter co-rdinates: x,y for each point ");
for(i=0;i<n;i++)
 scanf("%d%d",&xs[i],&ys[i]);
printf("Enter x shear factor:");
scanf("%f",&shearXfactor);
printf("Enter y shear factor:");
scanf("%f",&shearYfactor);

initgraph(&graDriver,&graMode,"C:\\TURBOC3\\BGI\\");
setcolor(RED);
DrawFn();//original
shearAlongX();
setcolor(BLUE);
DrawFn();//Xshear
shearAlongY();
setcolor(GREEN);
DrawFn();//Yshear
getch();

}
The above c program perform shear transformation on given polygon. You are asked to enter shear factors along x and y directions. The original polygon will be displayed in RED color. The polygon sheared horizontally is shown in BLUE color. The vertically sheared polygon is drawn in GREEN color.

No comments: