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

  • 本文关键字:情况下 SDL 绘制 外部 c++ sdl
  • 更新时间 :
  • 英文 :


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

为遇到相同问题的程序员提供最新答案。

在SDL2中,SDL_Render.h中有几个函数可以在不实现自己的绘制引擎或使用外部库的情况下实现这一点。

您可能想要使用:

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

其中renderer是您之前创建的渲染器,并且x1&y1表示开始;y2作为结尾。

还有一个替代函数,你可以立即用多个点画一条线,而不是多次调用上面提到的函数:

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

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

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

罗塞塔代码有一些例子:

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;
        }
    }
}

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

一些常见而简单的是:

数字差分分析仪(DDA)

Bresenham直线算法

吴的直线算法

最新更新