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 .
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.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With