Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a line using SDL without using external libraries

Tags:

c++

sdl

How can i draw a 2D line between two given points using SDL c++ library. I don't want to use any other external libraries like SDL_draw or SDL_gfx .

like image 562
rajat Avatar asked Dec 16 '22 21:12

rajat


2 Answers

Up-to-date answer for the coders who are struggling with the same issue.

In SDL2, there are a couple of functions in SDL_Render.h to achive this without implementing your own line drawing engine or using an external library.

You likely want to use:

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

Where renderer is the renderer you created before, and x1 & y1 are for the beginning, and x2 & y2 for the ending.

There is also an alternative function where you could draw a line with multiple points right away, instead of calling the mentioned function several times:

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

Where renderer is the renderer you created before, points is a fixed-array of the known points, and count the amount of points in that fixed-array.

All mentioned functions give a -1 back when error, and 0 on success.

like image 78
RoestVrijStaal Avatar answered Jan 31 '23 01:01

RoestVrijStaal


Rosetta Code has 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;
        }
    }
}
like image 38
genpfault Avatar answered Jan 31 '23 01:01

genpfault