Bitmap/Bresenham's line algorithm: Difference between revisions

m
Line 153:
=={{header|C}}==
 
Instead of swaps in the initialisation use error calculation for both directions x and y simultaneously:
To be added to <tt>imglib.h</tt>.
<lang C>void line(int x0, int y0, int x1, int y1) {
 
int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
<lang c>void draw_line(
int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;
image img,
int err = (dx>dy ? dx : -dy)/2, e2;
unsigned int x0, unsigned int y0,
unsigned int x1, unsigned int y1,
color_component r,
color_component g,
color_component b );</lang>
 
while(true){
The implementation code:
swap_uintsetPixel(x0, y0);
 
if (x0==x1 >&& x1y0==y1) {break;
<lang c>#include "imglib.h"
int ye2 = y0err;
 
if (e2 >-dx) { err -= dy; x0 += sx; }
#define plot(x, y) put_pixel_clip(img, x, y, r, g, b)
#define swap_uint(a, b) do{ unsignedif int(e2 tmp;< dy) tmp{ = a; aerr += bdx; by0 += tmpsy; }while(0)
}
 
}</lang>
void draw_line(
image img,
unsigned int x0, unsigned int y0,
unsigned int x1, unsigned int y1,
color_component r,
color_component g,
color_component b )
{
bool steep = abs(y1 - y0) > abs(x1 - x0);
if (steep) {
swap_uint(x0, y0);
swap_uint(x1, y1);
}
if (x0 > x1) {
swap_uint(x0, x1);
swap_uint(y0, y1);
}
int deltax = x1 - x0;
int deltay = abs(y1 - y0);
int error = deltax / 2;
int ystep;
int y = y0;
if (y0 < y1)
ystep = 1;
else
ystep = -1;
for (int x = x0; x <= x1; x++) {
if (steep)
plot(y, x);
else
plot(x, y);
error -= deltay;
if (error < 0) {
y += ystep;
error += deltax;
}
}
}
#undef swap_uint
#undef plot</lang>
 
=={{header|C++}}==