How to draw a line using SDL without using external libraries

12,800

Solution 1

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

Solution 2

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.

Solution 3

You can use any of the line drawing algorithms.

Some common and easy ones are:

Digital Differential Analyzer (DDA)

Bresenham's line algorithm

Xiaolin Wu's line algorithm

Share:
12,800

Related videos on Youtube

rajat
Author by

rajat

Updated on September 16, 2022

Comments

  • rajat
    rajat over 1 year

    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 .

  • James Clark
    James Clark over 11 years
    Probably don't want the coordinate arguments to be const if you are going to try to swap them.
  • Owl
    Owl over 5 years
    Seems like a good idea, until you try and display a photo or something then find you can't anymore because of the renderer.