直线裁剪

版权声明:欢迎转载,请注明出处噢,谢谢 https://blog.csdn.net/DT2131/article/details/78948167

基于编码裁剪和中点裁剪方法,将两种裁剪方法糅合到一起,补足了编码裁剪的不足(在编码裁剪无法判断时,进行中点裁剪,再判断)

使用了 EasyX 图形库,感谢 EasyX 团队


#include <bits/stdc++.h>
#include <graphics.h>
#include <conio.h>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
typedef struct Line {
	int stx, sty, enx, eny;
}Line;
const int MAXN = 1e5 + 7;
int n;
Line lines[MAXN];
int cnt, nc;
void input() {
	n = 0; cnt = 0; nc = 0;
	for (int i = 100; i <= 400; i += 10) lines[n++] = { i,100,250,250 };
	for (int i = 100; i <= 400; i += 10) lines[n++] = { i,400,250,250 };
	for (int i = 225; i <= 275; i += 3) lines[n++] = { 225,i,275,i };
	for (int i = 100; i <= 400; i += 10) lines[n++] = { i,100,i,400 };
}
void output() {
	for (int i = 0; i < n; i++) line(lines[i].stx+300, lines[i].sty, lines[i].enx+300, lines[i].eny);
}
int code(int x,int y,int lx,int dy,int rx,int uy) {
	cnt++;
	int ans = 0;
	if (x <= lx) {
		ans += 1 << 0;
	}
	else if (x >= rx) {
		ans += 1 << 1;
	}
	if (y <= dy) {
		ans += 1 << 2;
	}
	else if (y >= uy) {
		ans += 1 << 3;
	}
	//if (ans == 0) nc++;
	return ans;
}
void cut(Line a, int lx, int dy, int rx, int uy) {
	int code1 = code(a.stx, a.sty, lx, dy, rx, uy), code2 = code(a.enx, a.eny, lx, dy, rx, uy);
	if (code1 == 0 && code2 == 0) {
		nc++;
		line(a.stx, a.sty, a.enx, a.eny); return;
	}
	else if ((code1&code2)) {
		return;
	}
	int midx = (a.stx + a.enx) / 2, midy = (a.sty + a.eny) / 2;
	int flag1 = 0, flag2 = 0, flag3 = 0, flag4 = 0;
	if (a.stx > a.enx) flag1 = 1;
	if (a.stx < a.enx) flag2 = 1;
	if (a.sty > a.eny) flag3 = 1;
	if (a.sty < a.eny) flag4 = 1;
	cut({ a.stx, a.sty, midx + flag1, midy + flag3 }, lx, dy, rx, uy);
	if (code(midx + flag1, midy + flag3, lx, dy, rx, uy) == 0) putpixel(midx + flag1, midy + flag3, WHITE);
	cut({ midx + flag2, midy + flag4, a.enx, a.eny }, lx, dy, rx, uy);
	if (code(midx + flag2, midy + flag4, lx, dy, rx, uy) == 0) putpixel(midx + flag2, midy + flag4, WHITE);
}
void linecut(int lx, int dy, int rx, int uy) {
	for(int i=0;i<n;i++) cut(lines[i], lx, dy, rx, uy);
}
int main()
{
	initgraph(1366, 480);
	input();
	output();
	linecut(200, 200, 300, 300);
	system("pause");
    return 0;
}



猜你喜欢

转载自blog.csdn.net/DT2131/article/details/78948167