Task

Using the data storage type defined on the Bitmap page for raster graphics images,

draw a line given two points with Bresenham's line algorithm.




SegmentBresenham := proc (img, x0, y0, x1, y1) 
    local deltax, deltay, x, y, ystep, steep, err, img2, x02, y02, x12, y12; 
    x02, x12, y02, y12 := y0, y1, x0, x1; 
    steep := abs(x12 - x02) < abs(y12 - y02); 
    img2 := copy(img); 
    if steep then 
        x02, y02 := y02, x02; 
        x12, y12 := y12, x12; 
    end if; 
    if x12 < x02 then 
        x02, x12 := x12, x02;
        y02, y12 := y12, y02;
    end if; 
    deltax := x12 - x02; 
    deltay := abs(y12 - y02); 
    err := deltax / 2; 
    y := y02; 
    if y02 < y12 then
        ystep := 1
    else
        ystep := -1
    end if; 
    for x from x02 to x12 do 
        if steep then
            img2[y, x] := 0
        else
            img2[x, y] := 0
        end if; 
        err := err - deltay; 
        if err < 0 then 
            y := y + ystep; 
            err := err + deltax
        end if; 
    end do; 
    return img2;
end proc: