2012-07-31 64 views
3

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

+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 2012-07-31 10:24:07

回答

2

罗塞塔代码some examples

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

如果你想要交换它们,可能不希望坐标参数是const。 – 2013-01-17 22:16:34

2

您可以使用任何画线算法。

一些常见和简单的是:

数字微分分析仪(DDA)

Bresenham直线算法

吴小林直线算法

6

针对同一问题而苦苦挣扎的编码人员的最新答案。

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

你可能想使用:

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

哪里渲染器是你之前创建的渲染和x1 & Y1是开始,而X2 & Y2的结局。

也有另一种功能,你可以画多点线向右走,而不是调用所提到的功能几次:

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

渲染是你之前创建的渲染,分数是固定阵列的已知点数,并且计数该固定阵列中的点数。

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

相关问题