用c++编程实现二维cohen-sutherland裁剪算法
时间: 2023-10-17 07:05:36 浏览: 142
二维Cohen-Sutherland裁剪算法的C语言代码如下:
```
#include<stdio.h>
#include<graphics.h>
#define LEFT 1
#define RIGHT 2
#define BOTTOM 4
#define TOP 8
#define INSIDE 0
#define ROUND(a) ((int)(a + 0.5))
int xmin, ymin, xmax, ymax;
int computeCode(double x, double y)
{
int code = INSIDE;
if (x < xmin)
code |= LEFT;
else if (x > xmax)
code |= RIGHT;
if (y < ymin)
code |= BOTTOM;
else if (y > ymax)
code |= TOP;
return code;
}
void cohenSutherland(double x1, double y1, double x2, double y2)
{
int outcode1 = computeCode(x1, y1);
int outcode2 = computeCode(x2, y2);
int accept = 0;
while (1)
{
if (!(outcode1 | outcode2))
{
accept = 1;
break;
}
else if (outcode1 & outcode2)
break;
else
{
double x, y;
int outcode = outcode1 ? outcode1 : outcode2;
if (outcode & TOP)
{
x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1);
y = ymax;
}
else if (outcode & BOTTOM)
{
x = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1);
y = ymin;
}
else if (outcode & RIGHT)
{
y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1);
x = xmax;
}
else
{
y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1);
x = xmin;
}
if (outcode == outcode1)
{
x1 = x;
y1 = y;
outcode1 = computeCode(x1, y1);
}
else
{
x2 = x;
y2 = y;
outcode2 = computeCode(x2, y2);
}
}
}
if (accept)
line(ROUND(x1), ROUND(y1), ROUND(x2), ROUND(y2));
}
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
printf("Enter window coordinates (xmin ymin xmax ymax): ");
scanf("%d%d%d%d", &xmin, &ymin, &xmax, &ymax);
rectangle(xmin, ymin, xmax, ymax);
int n;
printf("Enter the number of lines: ");
scanf("%d", &n);
printf("Enter line coordinates (x1 y1 x2 y2):\n");
for (int i = 0; i < n; i++)
{
double x1, y1, x2, y2;
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
cohenSutherland(x1, y1, x2, y2);
}
getch();
closegraph();
return 0;
}
```
该代码实现的是以交互的方式输入最大可视区域大小和线段数量,并可以通过键盘按下任意键退出程序。
阅读全文