Draw Line
Posted: September 12th, 2017, 5:00 pm
In Chili's tutorial series years ago he taught us how to make a draw line function early on. I quit programming for quite and awhile and so I am going back through he new series again to brush up on my skills. I noticed that in this new series he does not show a draw line function. I've only made it to lesson 20 of the beginner series this may be something that he does indeed show later but I have yet to see it. I have found an excellent draw line function that works flawlessly(so far) and I just wanted to share it with the group.
Code: Select all
void Graphics::DrawLine(float x1, float y1, float x2, float y2, Color & color)
{
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)
{
PutPixel(y, x, color);
}
else
{
PutPixel(x, y, color);
}
error -= dy;
if (error < 0)
{
y += ystep;
error += dx;
}
}
}