Fix draw_lines for x1 = x2 and y1 = y2.

Some lines are dotted though.
This commit is contained in:
Fabien Freling 2014-06-22 16:08:40 +02:00
parent 70a828b651
commit 22546de9db

View file

@ -355,20 +355,33 @@ Image rotate(Image const& src, double angle)
void draw_line(Image& img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2) void draw_line(Image& img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2)
{ {
if (x1 > x2) int x_inc = x1 <= x2 ? 1 : -1;
{
swap(x1, x2);
swap(y1, y2);
}
unsigned int const y_min = min(y1, y2); unsigned int const y_min = min(y1, y2);
unsigned int const y_max = max(y1, y2); unsigned int const y_max = max(y1, y2);
double const slope = ((double) y2 - y1) / ((double) x2 - x1); double slope = (double) y2 - y1;
if (x1 != x2)
slope = ((double) y2 - y1) / abs((double) x2 - x1);
int y_inc = slope > 0 ? 1 : -1; int y_inc = slope > 0 ? 1 : -1;
unsigned int previous_y = y1; if (x1 == x2)
for (unsigned int i = x1; i <= x2; ++i)
{ {
unsigned int y = slope * (i - x1) + y1; for (unsigned int runner = y1; runner != y2; runner+= y_inc)
img.set_pixel(x1, runner, 255, 0, 0); // set line to red
return;
}
if (y1 == y2)
{
for (unsigned int runner = x1; runner != x2; runner+= x_inc)
img.set_pixel(runner, y1, 255, 0, 0); // set line to red
return;
}
unsigned int previous_y = y1;
for (unsigned int i = x1, steps = 0; i != x2; i += x_inc, ++steps)
{
unsigned int y = slope * steps + y1;
y = min(y, y_max); y = min(y, y_max);
y = max(y, y_min); y = max(y, y_min);
for (unsigned int runner = previous_y; runner != y; runner+= y_inc) for (unsigned int runner = previous_y; runner != y; runner+= y_inc)
@ -505,9 +518,13 @@ bool check_trigo()
void check_lines() void check_lines()
{ {
Image const square(500, 500); Image const square(500, 500);
draw_outline(square, 5, "square");
draw_outline(square, 12, "square");
draw_outline(square, 22, "square"); draw_outline(square, 22, "square");
draw_outline(square, 33, "square"); draw_outline(square, 33, "square");
draw_outline(square, 45, "square"); draw_outline(square, 45, "square");
draw_outline(square, 60, "square");
draw_outline(square, 75, "square");
draw_outline(square, 90, "square"); draw_outline(square, 90, "square");
Image const rect1(640, 480); Image const rect1(640, 480);