图形学-直线算法

图形学算法:DDA(Digital Differential Analyzer)

void lineDDA(int x0, int y0, int xEnd, int yEnd)
{
    float dx = xEnd - x0, dy = yEnd - y0, steps, k;
    float xInerement, yInerement, x = x0, y = y0;

    if (fabs(dx) > fabs(dy))
    {
        steps = fabs(dx);
    }
    else
    {
        steps = fabs(dy);
    }

    xInerement = float(dx) / float(steps);
    yInerement = float(dy) / float(steps);

    setPixel(round(x), round(y));

    for (k = 0; k < steps; k++)
    {
        x += xInerement;
        y += yInerement;
        setPixel(round(x), round(y));
    }
}

效果图:
技术分享

效果很差,线段部分不连续。

2. Bresenham‘s Line Algorithm

" We need to decide which of two possible pixel positions is closer to the line path at each sample step.
" Testing the sign of an integer parameter whose value is proportional to the difference between the vertical
  vertical separations of the two pixel positions from the actual line path.

void lineBres(int x0, int y0, int xEnd, int yEnd)
{
    int dx = abs(xEnd - x0), dy = abs(yEnd - y0);
    int p = 2 * dy - dx;
    int twoDy = 2 * dy, twoDyMinusDx = 2 * (dy - dx);
    int x, y;

    if (x0 > xEnd)
    {
        x = xEnd; 
        y = yEnd;
        xEnd = x0;
    }
    else
    {
        x = x0;
        y = y0;
    }

    setPixel(x, y);
    
    while (x < xEnd)
    {
        x++;
        if (p < 0)
            p += twoDy;
        else
        {
            y++;
            p += twoDyMinusDx;
        }

        setPixel(x, y);
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。