我目前正在尝试完成填充绘制的三角形的算法。我一直在做的方式是遍历形状并绘制单行。我有一个几乎完美的算法,除了一个小问题。当我有一个水平的一面时,填充失败。填充三角形算法
这是我目前的填充算法。我应该注意到称为origin,coor2和coor3的多维数组表示为我的三角形(origin [0] [0] =原点x,原点[0] [1] = y)的顶点。坐标是典型的窗口,(0,0)在左上角。此外,gc就是我需要在窗口中绘制的内容。
void triangle::drawFilled(GraphicsContext* gc)
{
// color
gc->setColor(colorRGB);
// algorithm variables
double ax = origin[0][0];
double bx = coor2[0][0];
double cx = coor3[0][0];
double ay = origin[1][0];
double by = coor2[1][0];
double cy = coor3[1][0];
// sort vertices by y
if (ay > by)
{
std::swap(ay, by);
std::swap(ax, bx);
}
if (ay > cy)
{
std::swap(ay, cy);
std::swap(ax, cx);
}
if (by > cy)
{
std::swap(by, cy);
std::swap(bx, cx);
}
// define more algorithm variables
double dx1 = (cx-ax)/(cy-ay);
double dx2 = (bx-ax)/(by-ay);
double dx3 = (cx-bx)/(cy-by);
double x1 = ax;
double x2 = ax;
// loop through coordinates
for(int y = ay; y < by; y++)
{
gc->drawLine(x1,y,x2,y);
x1 += dx1;
x2 += dx2;
}
// loop through coordinates
for(int y = by; y < cy; y++)
{
gc->drawLine(x1,y,x2,y);
x1 += dx1;
x2 += dx3;
}
}
Here's an example of my results when there are not horizontal sides
And here's when there is a horizontal side
注意如何外形和填充不排队。
我意识到问题可能在于y顶点的排序,因此不考虑x。我可以蛮横逼我的方法来处理水平和垂直边缘的所有情况,但这似乎效率很低。我宁愿学习如何解决我的困境,也不愿意解决它。