0

我正在使用这个 Bresenham 的算法来画圆。此代码有效,但我需要实心圆圈,而不仅仅是边框。

这是我的代码:

void setPixel(int x,int y)  {  
    glBegin(GL_POINTS); 
    glColor3f(0.0f, 1.0f, 0.0f);
    glPointSize (20.0);
    glVertex2i(x,y);
    glEnd();
}

void BresenhamKrug(int xCenter, int yCenter,int r){ //napravite parametarski poziv
int x=0,y=r;
int d=3-(2*r);

glColor3f(0.5,0.3,1.); 


while(x<=y)
{
    setPixel(xCenter+x,yCenter+y);  setPixel(xCenter+y,yCenter+x);
    setPixel(xCenter-x,yCenter+y);  setPixel(xCenter+y,yCenter-x); 
    setPixel(xCenter-x,yCenter-y);  setPixel(xCenter-y,yCenter-x); 
    setPixel(xCenter+x,yCenter-y);  setPixel(xCenter-y,yCenter+x); 

    if (d<0)
        d += (4*x)+6;
    else{
          d += (4*(x-y))+10;
          y--;
    }

    x++;
}
glFlush();
}

有什么办法吗?

4

2 回答 2

3

您可以将点保存在数组中并改为绘制多边形或三角形风扇

glBegin(GL_POLYGON);

或者:

void BresenhamKrug(int xCenter, int yCenter,int r){ //napravite parametarski poziv
    int x=0,y=r;
    int d=3-(2*r);

    glColor3f(0.5,0.3,1.); 

    glBegin(GL_POLYGON);

    while(x<=y)
    {
        glVertex2i(xCenter+x,yCenter+y);  glVertex2i(xCenter+y,yCenter+x);
        glVertex2i(xCenter-x,yCenter+y);  glVertex2i(xCenter+y,yCenter-x); 
        glVertex2i(xCenter-x,yCenter-y);  glVertex2i(xCenter-y,yCenter-x); 
        glVertex2i(xCenter+x,yCenter-y);  glVertex2i(xCenter-y,yCenter+x); 

        if (d<0)
            d += (4*x)+6;
        else{
              d += (4*(x-y))+10;
              y--;
        }

        x++;
    }
    glEnd();
    glFlush();
}

但不确定一个简单的圆方程是不够的。绘制圆,光栅化由openGL处理​​。

于 2014-03-25T18:59:33.367 回答
0

最简单的解决方案是修改算法,以便不用在边缘周围绘制像素,而是用线连接点。

void drawLine(const float x1, const float y1, const float x2, const float y2) {
    const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
    if(steep) {
        std::swap(x1, y1);
        std::swap(x2, y2);
    }

    if(x1 > x2) {
        std::swap(x1, x2);
        std::swap(y1, y2);
    }

    const float dx = x2 - x1;
    const float dy = fabs(y2 - y1);

    float error = dx / 2.0f;
    const int ystep = (y1 < y2) ? 1 : -1;
    int y = (int)y1;

    const int maxX = (int)x2;

    for(int x=(int)x1; x<maxX; x++) {
        if(steep) {
            setPixel(y,x);
        }
        else {
            setPixel(x,y);
        }

        error -= dy;
        if(error < 0) {
            y += ystep;
            error += dx;
        }
    }
}

void BresenhamKrug(int xCenter, int yCenter,int r){ //napravite parametarski poziv
    int x=0,y=r;
    int d=3-(2*r);
    glColor3f(0.5,0.3,1.);
    while(x<=y) {
        drawLine(xCenter+x,yCenter+y,  xCenter+y,yCenter+x);
        drawLine(xCenter-x,yCenter+y,  xCenter+y,yCenter-x); 
        drawLine(xCenter-x,yCenter-y,  xCenter-y,yCenter-x); 
        drawLine(xCenter+x,yCenter-y,  xCenter-y,yCenter+x); 
        if (d<0)
            d += (4*x)+6;
        else{
            d += (4*(x-y))+10;
            y--;
        }
        x++;
    }
    glFlush();
}

出于所有意图和目的,Bresenham 的线算法可能是最适合此的。

于 2014-03-25T19:11:47.193 回答