如何在不使用外部库的情况下使用SDL绘制直线

4

如何使用SDL C++库在两个给定点之间绘制2D线条。我不想使用任何其他外部库,如SDL_draw或SDL_gfx。


1
Bresenham线算法可能是一个解决方案。本文还涵盖了抗锯齿技术http://courses.engr.illinois.edu/ece390/archive/archive-f2000/mp/mp4/anti.html。另一个算法是:http://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm。 - nullpotent
3个回答

8

为了帮助遇到类似问题的编码人员,以下是最新的答案。

在SDL2中,SDL_Render.h中有几个函数可以实现此功能,无需实现自己的线条绘制引擎或使用外部库。

您可能需要使用以下函数:

 int SDL_RenderDrawLine( SDL_Renderer* renderer, int x1, int y1, int x2, int y2 );

在这里,renderer是之前创建的渲染器,x1和y1是起始点的坐标,x2和y2是结束点的坐标。

还有一种替代方法,可以一次性使用多个点绘制一条直线,而不是多次调用上述函数:

 int SDL_RenderDrawPoints( SDL_Renderer* renderer, const SDL_Point* points, int count );

其中renderer是您之前创建的渲染器,points是已知点的固定数组,count是该固定数组中点的数量。

所有提到的函数在出错时返回-1,在成功时返回0。


似乎是个好主意,直到你尝试显示一张照片或其他东西,然后发现由于渲染器的原因无法再这样做了。 - Owl

2

Rosetta Code有一些例子

void Line( float x1, float y1, float x2, float y2, const Color& color )
{
    // Bresenham's line algorithm
    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, color);
        }
        else
        {
            SetPixel(x,y, color);
        }

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

1
如果你想要尝试交换它们,那么可能不希望坐标参数是const。 - James Clark

2

您可以使用任何一种线绘制算法。

一些常见而简单的算法包括:

数字微分分析法(DDA)

布雷森汉姆线算法

吴小林线算法


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接