1
General / Re: Bresenham Line Implementation in C++
« on: June 28, 2018, 05:14:58 pm »
void BresenhamLine(sf::Image& MyImage, char * outFN, float x1, float y1, float x2, float y2)
{
int width = img.getSize().x;
int height = img.getSize().y;
int y = 0;
const int maxX = (int)x2;
const int ystep = (y1 < y2) ? 1 : -1;
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 2.0f;
const bool Slope = (fabs(y2 - y1) > fabs(x2 - x1));
//MyImage
sf::Image output = MyImage;
//Main Loop
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
//The Run
if (img.getPixel(x, y) == sf::Color::Black && Slope == true)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if (img.getPixel(x, y) == sf::Color::Black && x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
}
//The Rise
for (int x = (int)x1; x < maxX; x++)
{
if (img.getPixel(x, y) != sf::Color::White && Slope == true)
{
output.setPixel(x, y, sf::Color::Red);
}
else
{
output.setPixel(y, x, sf::Color::Green);
}
error -= dy;
if (error < 0)
{
y += ystep;
error += dx;
}
}
}
//The Output Function
output.saveToFile(outFN);
}
{
int width = img.getSize().x;
int height = img.getSize().y;
int y = 0;
const int maxX = (int)x2;
const int ystep = (y1 < y2) ? 1 : -1;
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 2.0f;
const bool Slope = (fabs(y2 - y1) > fabs(x2 - x1));
//MyImage
sf::Image output = MyImage;
//Main Loop
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
//The Run
if (img.getPixel(x, y) == sf::Color::Black && Slope == true)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if (img.getPixel(x, y) == sf::Color::Black && x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
}
//The Rise
for (int x = (int)x1; x < maxX; x++)
{
if (img.getPixel(x, y) != sf::Color::White && Slope == true)
{
output.setPixel(x, y, sf::Color::Red);
}
else
{
output.setPixel(y, x, sf::Color::Green);
}
error -= dy;
if (error < 0)
{
y += ystep;
error += dx;
}
}
}
//The Output Function
output.saveToFile(outFN);
}