码迷,mamicode.com
首页 > 编程语言 > 详细

图形学-直线算法

时间:2015-02-25 16:55:00      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

图形学算法: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);
    }
}

 

图形学-直线算法

标签:

原文地址:http://www.cnblogs.com/x5lcfd/p/4299694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!