Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*AIM:TO IMPLEMENT LIANG BARSKY LINE CLIPPING ALGORITHM
- NAME:HARSH HEMRAJANI
- BATCH:C12
- ROLL NO:33
- */
- import java.util.*;
- import java.applet.Applet;
- import java.awt.*;
- class Clipper
- {
- int WXmin,WYmin,WXmax,WYmax;
- double u1,u2;
- public Clipper(Rectangle r) //Constructor initializes window parameters
- {
- WXmax=(int)r.getMaxX();
- WXmin=(int)r.getMinX();
- WYmax=(int)r.getMaxY();
- WYmin=(int)r.getMinY();
- }
- public void clip(Point p1,Point p2,Graphics g) //Clips the line
- {
- int dx,dy,a,b;
- boolean done=false;
- g.drawRect(WXmin,WYmin,WXmax-WXmin,WYmax-WYmin); //Drawing window
- u1=0;u2=1;
- dx=p2.x-p1.x;
- dy=p2.y-p1.y;
- a=p1.x;b=p1.y;
- if(clipTest(-dx,p1.x-WXmin))
- if(clipTest(dx,WXmax-p1.x))
- if(clipTest(-dy,p1.y-WYmin))
- if(clipTest(dy,WYmax-p1.y))
- {
- done=true;
- if(u1>0)
- {
- p1.x=a+(int)(u1*(double)dx);
- p1.y=b+(int)(u1*(double)dy);
- }
- if(u2<1)
- {
- p2.x=a+(int)(u2*(double)dx);
- p2.y=b+(int)(u2*(double)dy);
- }
- if(u1==0 && u2==1)
- {
- System.out.println("Line is completely inside");
- g.drawLine(p1.x,p1.y,p2.x,p2.y);
- return;
- }
- }
- if(!done)
- {
- System.out.println("Line is completely outside the window");
- return;
- }
- System.out.println("\nCo-ordinates of clipped line:");
- System.out.println(p1.x+" "+p1.y);
- System.out.println(p2.x+" "+p2.y);
- g.drawLine(p1.x,p1.y,p2.x,p2.y);
- }
- private boolean clipTest(double p,double q)
- {
- double r=q/p;
- boolean okay=true;
- if(p<0)
- {
- if(r>u2)
- okay=false;
- else if(r>u1)
- u1=r;
- }
- else if(p>0)
- {
- if(r<u1)
- okay=false;
- else if(r<u2)
- u2=r;
- }
- else if(q<0)
- okay=false;
- return okay;
- }
- }
- public class LiangClip extends Applet
- {
- Point p1,p2; Clipper win;
- public void init()
- {
- this.setSize(800, 800);
- Scanner sc=new Scanner(System.in);
- System.out.println("Enter the parameters of clipping window:");
- System.out.print("Left top point:");
- int rx=sc.nextInt();
- int ry=sc.nextInt();
- System.out.print("Width:");
- int w=sc.nextInt();
- System.out.print("Height:");
- int h=sc.nextInt();
- Rectangle r=new Rectangle(rx,ry,w,h);
- win=new Clipper(r);
- System.out.println("\nEnter the end points of a line:");
- p1=new Point(sc.nextInt(),sc.nextInt());
- p2=new Point(sc.nextInt(),sc.nextInt());
- }
- public void paint(Graphics g)
- {
- win.clip(p1,p2,g);
- }
- }
- /*OUTPUT:
- Enter the parameters of clipping window:
- Left top point:
- 225 225
- Width:180
- Height:135
- Enter the end points of a line:
- 125 400
- 420 180
- Co-ordinates of clipped line:
- 225 326
- 359 225
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement