⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cs线段裁剪.java

📁 用java写的cs线段裁剪
💻 JAVA
字号:
import java.applet.*;
import java.awt.*;
class OutCode
{
	int all;
	float left,right,top,bottom;
}
public class CS线段裁剪 extends Applet{

	private Button bt=null;
	private float x0,y0,x1,y1;
	private boolean clear=false;
	private boolean ok=false;
	public void init()
	{
		bt=new Button("清除");
		this.setSize(500,400);
		this.add(bt);
	}
	public void paintLine(Graphics g)
	{
		g.setColor(Color.black);
		g.drawLine(100, 0, 100, 400);
		g.drawLine(400, 0, 400, 400);
		g.drawLine(0, 50, 500, 50);
		g.drawLine(0, 250, 500, 250);
	}
	public boolean mouseDown(Event e,int x,int y)//线段起点
	{
		x0=x;
		y0=y;
		repaint();
		return true;
	}
	public boolean mouseUp(Event e,int x,int y)//线段终点
	{
		x1=x;
		y1=y;
		repaint();
		ok=true;
		return true;
	}
	public void compOutCode(float x,float y,OutCode outCode)//计算(x,y)的编码
	{
		outCode.all=0;
		outCode.top=outCode.bottom=0;
		if(y>250)
		{
			outCode.top=1;
			outCode.all+=1;
		}
		else if(y<50)
		{
			outCode.bottom=1;
			outCode.all+=1;
		}
		outCode.left=outCode.right=0;
		if(x>400)
		{
			outCode.right=1;
			outCode.all+=1;
		}
		else if(x<100)
		{
			outCode.left=1;
			outCode.all+=1;
		}
	}
	public void CSLineClip(float x0,float y0,float x1,float y1,Graphics g)
	{
		boolean accept,done;
		OutCode outCode0,outCode1;
		OutCode outCode=null;
		float x,y;
		outCode0=new OutCode();
		compOutCode(x0,y0,outCode0);
		outCode1=new OutCode();
		compOutCode(x1,y1,outCode1);
		accept=done=false;
		x=0;
		y=0;
		
		do
		{
			if(outCode0.all==0&&outCode1.all==0)
			{
				accept=true;
				done=true;
			}
			else if((outCode0.all&outCode1.all)!=0)
				done=true;
			else
			{
				if(outCode0.all!=0)
					outCode=outCode0;
				else
					outCode=outCode1;
				if(outCode.left!=0)
				{
					y=y0+(y1-y0)*(100-x0)/(x1-x0);
					x=100;
				}
				else if(outCode.top!=0)
				{
					x=x0+(x1-x0)*(250-y0)/(y1-y0);
					y=250;
				}
				else if(outCode.right!=0)
				{
					y=y0+(y1-y0)*(400-x0)/(x1-x0);
					x=400;
				}
				else if(outCode.bottom!=0)
				{
					x=x0+(x1=x0)*(50-x0)/(y1-y0);
					y=50;
				}
				if(outCode.all==outCode0.all)
				{
					x0=x;
					y0=y;
					compOutCode(x0,y0,outCode0);
				}
				else
				{
					x1=x;
					y1=y;
					compOutCode(x1,y1,outCode1);
				}
			}
		}while(!done);
		if(accept)
		{
			g.setColor(Color.red);
			g.drawLine((int)x0, (int)y0, (int)x1, (int)y1);
		}
	}
	public void paint(Graphics g)
	{
		paintLine(g);
		if(ok)
		{
			CSLineClip(x0,y0,x1,y1,g);
			ok=false;
		}
		
		if(clear)
		{
			g.clearRect(0,0, 500, 300);
			paintLine(g);
			clear=false;
		}
	}
	public void update(Graphics g)
	{
		paint(g);
	}
	public boolean action(Event e,Object obj)
	{
		if(e.target==bt)
		{
			clear=true;
			repaint();
		}
		return true;
	}
 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -