如何使用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是起始点的坐标,x2和y2是结束点的坐标。
还有一种替代方法,可以一次性使用多个点绘制一条直线,而不是多次调用上述函数:
int SDL_RenderDrawPoints( SDL_Renderer* renderer, const SDL_Point* points, int count );
其中renderer是您之前创建的渲染器,points是已知点的固定数组,count是该固定数组中点的数量。
所有提到的函数在出错时返回-1,在成功时返回0。
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;
}
}
}
您可以使用任何一种线绘制算法。
一些常见而简单的算法包括:
数字微分分析法(DDA)
布雷森汉姆线算法
吴小林线算法