我正在思考如何将一个圆裁剪到矩形边界框内?目前我的程序中使用了Cohen-Sutherland算法来进行线段裁剪,我已经成功地实现了矩形和多边形的裁剪。然而,在对圆进行裁剪时,我不知道该如何处理。我使用以下代码构建我的圆:
glBegin(GL_POLYGON);
double radius = 50;
for(int angle = 0; angle <= 360; angle++ ){
float const curve = 2 * PI * (float)angle / (float)360;
glVertex2f(point.x + sin(curve) * radius, point.y + cos(curve) * radius);
}
glEnd();
我的裁剪算法与此处相同:http://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm。然而,它返回表示新行的两个点,以后可以用来绘制被裁剪的形状。因此,基本上我尝试这样做:
line Lines[360] // an array with size 360 with data type line, which is a struct holding two points (x1, y1, x2, y2) of the new line returned by my clipping function.
double radius = 50;
for(int angle = 0; angle < 360; angle++){
float const currentCurve = 2 * PI * (float)angle / (float)360;
float const nextCurve = 2 * PI * (float)(angle+1) / (float)360;
int x1 = (int)(point[i].x + sin(currentCurve) * radius); // point is another struct holding only a single point.
y1 = (int)(point[i].y + cos(currentCurve) * radius);
x2 = (int)(point[i+1].x+ sin(nextCurve) * radius);
y2 = (int)(point[i+1].y + cos(nextCurve) * radius);=
// Clip the points with the clipping algorithm:
Lines[i] = Clipper(x1, y1, x2, y2);
}
// Once all lines have been clipped or not, draw:
glBegin(GL_POLYGON);
for(int i = 0; i < 360; i++){
glVertex2f(Lines[i].x1, Lines[i].y1);
glVertex2f(Lines[i].x2, Lines[i].y2);
}
glEnd();
请注意,我使用鼠标在屏幕上画了一个圆,并将每个360个点存储到名为point的结构体数组中,该数组是链表的一部分。因此,我有一个节点代表屏幕上的一个圆。
不过,即使如此,我的圆并没有被裁剪(或者根本没有被绘制出来),而且我的应用程序在几次鼠标单击后崩溃了。