用C++写一个liang-barsky算法
时间: 2023-03-12 11:51:44 浏览: 81
我可以为您提供一份简单的liang-barsky算法的C语言实现: #include<stdio.h>
// Function to clip a line from P1 = (x2, y2) to P2 = (x2, y2)
void liangBarsky(int x1, int y1, int x2, int y2)
{
// Defining region codes
int code1 = computeCode(x1, y1);
int code2 = computeCode(x2, y2); // Initializing parameters
float m = (float)(y2 - y1) / (x2 - x1);
int x, y; // Calculating intersection
while (true)
{
// Bitwise OR is used to find the outcode
if ((code1 | code2) == 0)
{
// Logical AND is used to accept and reject
if ((code1 & code2) == 0)
{
x = x2;
y = y2;
break;
}
else
break;
}
else
{
int code_out;
float xi = x2, yi = y2; // Find the point outside rectangle
if (code1 != 0)
code_out = code1;
else
code_out = code2; // Find intersection point
if (code_out & TOP)
{
xi = x1 + (y_max - y1) / m;
yi = y_max;
}
else if (code_out & BOTTOM)
{
xi = x1 + (y_min - y1) / m;
yi = y_min;
}
else if (code_out & RIGHT)
{
yi = y1 + m * (x_max - x1);
xi = x_max;
}
else if (code_out & LEFT)
{
yi = y1 + m * (x_min - x1);
xi = x_min;
} // Now intersection point x,y is found
// We replace point outside rectangle by intersection point
if (code_out == code1)
{
x1 = xi;
y1 = yi;
code1 = computeCode(x1, y1);
}
else
{
x2 = xi;
y2 = yi;
code2 = computeCode(x2, y2);
}
}
} printf("Line accepted from %d, %d to %d, %d", x1, y1, x, y);
} // Implementing Cohen-Sutherland algorithm
int computeCode(int x, int y)
{
int code = INSIDE;
if (x < x_min) // to the left of rectangle
code |= LEFT;
else if (x > x_max) // to the right of rectangle
code |= RIGHT;
if (y < y_min) // below the rectangle
code |= BOTTOM;
else if (y > y_max) // above the rectangle
code |= TOP; return code;
} // Driver program to test above functions
int main()
{
// Coordinates of rectangle
int x_min = 10, y_min = 20;
int x_max = 20, y_max = 40; // Coordinates of line
int x1 = 30, y1 = 10;
int x2 = 40, y2 = 50; liangBarsky(x1, y1, x2, y2);
return 0;
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)