Bitmap/Bresenham's line algorithm: Difference between revisions

(→‎{{header|C++}}: minor bug fixed)
imported>Chinhouse
 
(44 intermediate revisions by 20 users not shown)
Line 1:
{{task|Raster graphics operations}}
[[Category:Graphics algorithms]]
[[Category:Geometry]]
{{task|Raster graphics operations}}
 
;Task:
Using the data storage type defined on the [[Bitmap]] page for raster graphics images, draw a line given two points with [[wp:Bresenham's line algorithm|Bresenham's line algorithm]].
<br>draw a line given two points with [[wp:Bresenham's line algorithm|Bresenham's line algorithm]].
<br><br>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">T Colour
Byte r, g, b
 
F (r, g, b)
.r = r
.g = g
.b = b
 
F ==(other)
R .r == other.r & .g == other.g & .b == other.b
 
V black = Colour(0, 0, 0)
V white = Colour(255, 255, 255)
 
T Bitmap
Int width, height
Colour background
[[Colour]] map
 
F (width = 40, height = 40, background = white)
assert(width > 0 & height > 0)
.width = width
.height = height
.background = background
.map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))
 
F fillrect(x, y, width, height, colour = black)
assert(x >= 0 & y >= 0 & width > 0 & height > 0)
L(h) 0 .< height
L(w) 0 .< width
.map[y + h][x + w] = colour
 
F chardisplay()
V txt = .map.map(row -> row.map(bit -> (I bit == @@.background {‘ ’} E ‘@’)).join(‘’))
txt = txt.map(row -> ‘|’row‘|’)
txt.insert(0, ‘+’(‘-’ * .width)‘+’)
txt.append(‘+’(‘-’ * .width)‘+’)
print(reversed(txt).join("\n"))
 
F set(x, y, colour = black)
.map[y][x] = colour
 
F get(x, y)
R .map[y][x]
 
F line(x0, y0, x1, y1)
‘Bresenham's line algorithm’
V dx = abs(x1 - x0)
V dy = abs(y1 - y0)
V (x, y) = (x0, y0)
V sx = I x0 > x1 {-1} E 1
V sy = I y0 > y1 {-1} E 1
I dx > dy
V err = dx / 2.0
L x != x1
.set(x, y)
err -= dy
I err < 0
y += sy
err += dx
x += sx
E
V err = dy / 2.0
L y != y1
.set(x, y)
err -= dx
I err < 0
x += sx
err += dy
y += sy
.set(x, y)
 
V bitmap = Bitmap(17, 17)
L(x0, y0, x1, y1) ((1, 8, 8, 16), (8, 16, 16, 8), (16, 8, 8, 1), (8, 1, 1, 8))
bitmap.line(x0, y0, x1, y1)
bitmap.chardisplay()</syntaxhighlight>
 
{{out}}
<pre>
+-----------------+
| @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @|
| @ @ |
| @ @ |
| @ @@ |
| @ @ |
| @ @ |
| @ @ |
| @ |
| |
+-----------------+
</pre>
=={{header|360 Assembly}}==
{{trans|Rexx}}
<langsyntaxhighlight lang="360asm">* Bitmap/Bresenham's line algorithm - 13/05/2019
BRESENH CSECT
USING BRESENH,R13 base register
Line 195 ⟶ 298:
PG DC CL80' ' buffer
REGEQU
END BRESENH </langsyntaxhighlight>
{{out}}
<pre>
Line 219 ⟶ 322:
...|....................
</pre>
=={{header|Action!}}==
Part of the task is available in [http://www.rosettacode.org/wiki/Category:Action!_Bitmap_tools#RGBLINE.ACT RGBLINE.ACT].
{{libheader|Action! Bitmap tools}}
<syntaxhighlight lang="action!">INCLUDE "H6:RGBLINE.ACT" ;from task Bresenham's line algorithm
 
RGB black,yellow,violet,blue
 
PROC DrawImage(RgbImage POINTER img BYTE x,y)
RGB POINTER ptr
BYTE i,j
 
ptr=img.data
FOR j=0 TO img.h-1
DO
FOR i=0 TO img.w-1
DO
IF RgbEqual(ptr,yellow) THEN
Color=1
ELSEIF RgbEqual(ptr,violet) THEN
Color=2
ELSEIF RgbEqual(ptr,blue) THEN
Color=3
ELSE
Color=0
FI
Plot(x+i,y+j)
ptr==+RGBSIZE
OD
OD
RETURN
 
PROC Main()
RgbImage img
BYTE CH=$02FC,width=[81],height=[51],st=[5]
BYTE ARRAY ptr(12393)
BYTE c,i,n
INT x,y,nx,ny
RGB POINTER col
 
Graphics(7+16)
SetColor(0,13,12) ;yellow
SetColor(1,4,8) ;violet
SetColor(2,8,6) ;blue
SetColor(4,0,0) ;black
 
RgbBlack(black)
RgbYellow(yellow)
RgbViolet(violet)
RgbBlue(blue)
 
InitRgbImage(img,width,height,ptr)
FillRgbImage(img,black)
 
nx=width/st ny=height/st
FOR n=0 TO 2*nx+2*ny-1
DO
IF n MOD 3=0 THEN col=yellow
ELSEIF n MOD 3=1 THEN col=violet
ELSE col=blue FI
 
IF n<nx THEN
x=n*st y=0
ELSEIF n<nx+ny THEN
x=width-1 y=(n-nx)*st
ELSEIF n<2*nx+ny THEN
x=width-1-(n-nx-ny)*st y=height-1
ELSE
x=0 y=height-1-(n-2*nx-ny)*st
FI
RgbLine(img,width/2,height/2,x,y,col)
OD
 
DrawImage(img,(160-width)/2,(96-height)/2)
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bresenham's_line_algorithm.png Screenshot from Atari 8-bit computer]
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">procedure Line (Picture : in out Image; Start, Stop : Point; Color : Pixel) is
DX : constant Float := abs Float (Stop.X - Start.X);
DY : constant Float := abs Float (Stop.Y - Start.Y);
Line 261 ⟶ 441:
end if;
Picture (X, Y) := Color; -- Ensure dots to be drawn
end Line;</langsyntaxhighlight>
The test program's
<langsyntaxhighlight lang="ada"> X : Image (1..16, 1..16);
begin
Fill (X, White);
Line 270 ⟶ 450:
Line (X, (16, 8), ( 8, 1), Black);
Line (X, ( 8, 1), ( 1, 8), Black);
Print (X);</langsyntaxhighlight>
sample output
<pre>
Line 290 ⟶ 470:
H
</pre>
 
=={{header|ALGOL 68}}==
{{trans|Ada}}
Line 296 ⟶ 475:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.6 algol68g-2.6].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: prelude/Bitmap/Bresenhams_line_algorithm.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID:
Line 337 ⟶ 516:
END # line #;
 
SKIP</langsyntaxhighlight>'''File: test/Bitmap/Bresenhams_line_algorithm.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
Line 352 ⟶ 531:
(line OF class image)(x, ( 8, 1), ( 1, 8), black OF class image);
(print OF class image)(x)
)</langsyntaxhighlight>'''Output:'''
<pre>
ffffffffffffffffffffffffffffffffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffffff
Line 371 ⟶ 550:
ffffffffffffffffffffffffffffffffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffffff
</pre>
=={{header|Applesoft BASIC}}==
 
<syntaxhighlight lang="gwbasic"> 10 HGR :FULLSCREEN = PEEK (49234)
20 HCOLOR= 3
30 FOR N = 3 TO 279 STEP 4
40 X1 = 276:Y1 = 189:X2 = N:Y2 = 1: GOSUB 100"PLOT LINE"
50 NEXT N
60 FOR N = 3 TO 191 STEP 3
70 X1 = 276:Y1 = 190:X2 = 2:Y2 = N: GOSUB 100"PLOT LINE"
80 NEXT N
90 END
100 DX = ABS (X2 - X1)
110 SX = SGN (X2 - X1)
120 DY = - ABS (Y2 - Y1)
130 SY = SGN (Y2 - Y1)
140 ERR = DX + DY
150 FOR WHILE = 0 TO 1 STEP 0
160 HPLOT X1,Y1
170 IF X1 = X2 AND Y1 = Y2 THEN RETURN
180 E2 = 2 * ERR
190 IF E2 > = DY AND X1 = X2 THEN RETURN
200 IF E2 > = DY THEN ERR = ERR + DY:X1 = X1 + SX
210 IF E2 < = DX AND Y1 = Y2 THEN RETURN
220 IF E2 < = DX THEN ERR = ERR + DX:Y1 = Y1 + SY
230 NEXT WHILE</syntaxhighlight>
=={{header|Assembly}}==
16 bit Intel 8086\80486 Assembly for dos, see [http://en.wikipedia.org/wiki/X86_assembly_language x86 assembly language].
Line 571 ⟶ 773:
END start
</pre>
=={{header|ATS}}==
See [[Bresenham_tasks_in_ATS]].
 
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">Blue := Color(0,0,255)
White := Color(255,255,255)
Bitmap := Bitmap(100,100,Blue) ;create a 100*100 blue bitmap
Line 592 ⟶ 796:
Temp1 := ErrorValue << 1, ((Temp1 > DeltaY) ? (ErrorValue += DeltaY, PosX1 += StepX) : ""), ((Temp1 < DeltaX) ? (ErrorValue += DeltaX, PosY1 += StepY) : "") ;move forward
}
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">Local $var = drawBresenhamLine(2, 3, 2, 6)
 
Func drawBresenhamLine($iX0, $iY0, $iX1, $iY1)
Line 618 ⟶ 822:
EndIf
WEnd
EndFunc ;==>drawBresenhamLine</langsyntaxhighlight>
 
=={{header|bash}}==
<langsyntaxhighlight lang="bash">#! /bin/bash
 
function line {
Line 683 ⟶ 886:
line $((COLS/2)) $LINS $((COLS/4*3)) $((LINS/2))
line $((COLS/4*3)) $((LINS/2)) $((COLS/2)) 1
echo -e "\e[${LINS}H"</langsyntaxhighlight>
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="qbasic"> 1500 REM === Draw a line. Ported from C version
1510 REM Inputs are X1, Y1, X2, Y2: Destroys value of X1, Y1
1520 DX = ABS(X2 - X1):SX = -1:IF X1 < X2 THEN SX = 1
Line 697 ⟶ 899:
1590 IF E2 > -DX THEN ER = ER - DY:X1 = X1 + SX
1600 IF E2 < DY THEN ER = ER + DX:Y1 = Y1 + SY
1610 GOTO 1560</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> Width% = 200
Height% = 200
REM Set window size:
VDU 23,22,Width%;Height%;8,16,16,128
REM Draw lines:
PROCbresenham(50,100,100,190,0,0,0)
PROCbresenham(100,190,150,100,0,0,0)
PROCbresenham(150,100,100,10,0,0,0)
PROCbresenham(100,10,50,100,0,0,0)
END
DEF PROCbresenham(x1%,y1%,x2%,y2%,r%,g%,b%)
LOCAL dx%, dy%, sx%, sy%, e
dx% = ABS(x2% - x1%) : sx% = SGN(x2% - x1%)
dy% = ABS(y2% - y1%) : sy% = SGN(y2% - y1%)
IF dx% > dy% e = dx% / 2 ELSE e = dy% / 2
REPEAT
PROCsetpixel(x1%,y1%,r%,g%,b%)
IF x1% = x2% IF y1% = y2% EXIT REPEAT
IF dx% > dy% THEN
x1% += sx% : e -= dy% : IF e < 0 e += dx% : y1% += sy%
ELSE
y1% += sy% : e -= dx% : IF e < 0 e += dy% : x1% += sx%
ENDIF
UNTIL FALSE
ENDPROC
DEF PROCsetpixel(x%,y%,r%,g%,b%)
COLOUR 1,r%,g%,b%
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC</lang>
[[File:bresenham_bbc.gif]]
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 865 ⟶ 1,028:
)
)
goto :eof</langsyntaxhighlight>
=={{header|BBC BASIC}}==
 
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> Width% = 200
Height% = 200
REM Set window size:
VDU 23,22,Width%;Height%;8,16,16,128
REM Draw lines:
PROCbresenham(50,100,100,190,0,0,0)
PROCbresenham(100,190,150,100,0,0,0)
PROCbresenham(150,100,100,10,0,0,0)
PROCbresenham(100,10,50,100,0,0,0)
END
DEF PROCbresenham(x1%,y1%,x2%,y2%,r%,g%,b%)
LOCAL dx%, dy%, sx%, sy%, e
dx% = ABS(x2% - x1%) : sx% = SGN(x2% - x1%)
dy% = ABS(y2% - y1%) : sy% = SGN(y2% - y1%)
IF dx% > dy% e = dx% / 2 ELSE e = dy% / 2
REPEAT
PROCsetpixel(x1%,y1%,r%,g%,b%)
IF x1% = x2% IF y1% = y2% EXIT REPEAT
IF dx% > dy% THEN
x1% += sx% : e -= dy% : IF e < 0 e += dx% : y1% += sy%
ELSE
y1% += sy% : e -= dx% : IF e < 0 e += dy% : x1% += sx%
ENDIF
UNTIL FALSE
ENDPROC
DEF PROCsetpixel(x%,y%,r%,g%,b%)
COLOUR 1,r%,g%,b%
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC</syntaxhighlight>
[[File:bresenham_bbc.gif]]
=={{header|C}}==
 
Instead of swaps in the initialisation use error calculation for both directions x and y simultaneously:
<langsyntaxhighlight Clang="c">void line(int x0, int y0, int x1, int y1) {
 
int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
Line 883 ⟶ 1,082:
if (e2 < dy) { err += dx; y0 += sy; }
}
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Port of the C version.
<langsyntaxhighlight lang="csharp">using System;
using System.Drawing;
using System.Drawing.Imaging;
Line 913 ⟶ 1,111:
return bitmap;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
void Line( const float x1, const float y1, const float x2, const float y2, const Color& color )
{
// Bresenham's line algorithm
Line 961 ⟶ 1,158:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">
 
(defn draw-line
Line 990 ⟶ 1,186:
(recur (inc x) (+ y y-step) (+ error (- delta-x delta-y)))
(recur (inc x) y (- error delta-y)))))))))))
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
 
<langsyntaxhighlight lang="coffeescript">
drawBresenhamLine = (x0, y0, x1, y1) ->
dx = Math.abs(x1 - x0)
Line 1,013 ⟶ 1,208:
y0 += sy
null
</syntaxhighlight>
</lang>
=={{header|Commodore BASIC}}==
 
<syntaxhighlight lang="basic">
=={{header|Commodore Basic}}==
<lang CommodoreBasic>
10 rem bresenham line algorihm
20 rem translated from purebasic
Line 1,055 ⟶ 1,249:
2050 if sl<(sw*sh) then poke sc+sl,pc
2060 return
</syntaxhighlight>
</lang>
[https://www.worldofchris.com/assets/c64-bresenham-line.png C64 Example screenshot]
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun draw-line (buffer x1 y1 x2 y2 pixel)
(declare (type rgb-pixel-buffer buffer))
(declare (type integer x1 y1 x2 y2))
Line 1,087 ⟶ 1,280:
(incf y y-step)
(incf error delta-x))))
buffer))</langsyntaxhighlight>
 
=={{header|D}}==
This code uses the Image defined in [[Bitmap]] Task.
 
<langsyntaxhighlight lang="d">module bitmap_bresenhams_line_algorithm;
 
import std.algorithm, std.math, bitmap;
Line 1,143 ⟶ 1,335:
img.textualShow();
}
}</langsyntaxhighlight>
To run the demo code compile with <code>-version=bitmap_bresenhams_line_algorithm_main</code>.
{{out}}
Line 1,168 ⟶ 1,360:
###.###########.#########
#########################</pre>
 
=={{header|Delphi}}==
 
<langsyntaxhighlight lang="delphi">
procedure drawLine (bitmap : TBitmap; xStart, yStart, xEnd, yEnd : integer; color : TAlphaColor);
// Bresenham's Line Algorithm. Byte, March 1988, pp. 249-253.
Line 1,244 ⟶ 1,435:
end;
end;
</syntaxhighlight>
</lang>
=={{header|E}}==
 
{{trans|C}}
 
<syntaxhighlight lang="e">def swap(&left, &right) { # From [[Generic swap]]
def t := left
left := right
right := t
}
 
def drawLine(image, var x0, var y0, var x1, var y1, color) {
def steep := (y1 - y0).abs() > (x1 - x0).abs()
if (steep) {
swap(&x0, &y0)
swap(&x1, &y1)
}
if (x0 > x1) {
swap(&x0, &x1)
swap(&y0, &y1)
}
def deltax := x1 - x0
def deltay := (y1 - y0).abs()
def ystep := if (y0 < y1) { 1 } else { -1 }
var error := deltax // 2
var y := y0
for x in x0..x1 {
if (steep) { image[y, x] := color } else { image[x, y] := color }
error -= deltay
if (error < 0) {
y += ystep
error += deltax
}
}
}</syntaxhighlight>
 
<syntaxhighlight lang="e">def i := makeImage(5, 20)
drawLine(i, 1, 1, 3, 18, makeColor.fromFloat(0,1,1))
i.writePPM(<import:java.io.makeFileOutputStream>(<file:~/Desktop/Bresenham.ppm>))</syntaxhighlight>
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=XZHNboMwEITvPMUeG0W4NrSHSnHehQRHQkoJMiRl3z6zePkrAsv7MTNe2118XKnrw0AjMRkyGRH9Pl4B9Sd9gWEUFsN1IGuK72nITNaJs47V371pobbElkZH7OaUeiRP1aWnD+AcioPQXmjuZNrcxHaCS6r531SkAJ4DWAJYA3gbwBLASwDvAkKMokVO3byoUAv6OiNbLUkDtkhM2m4XqkE16Xxkhwqe7dDchXjZctXW0odf+wgFKiRriUVBzuhkVKIL535tBA8Cjx6noMTs7KedVNxH6XtFnNy8dRtc1HJHhbXk5LUyXbmC6St/7N4AQOV/R7lxOJu9AQ== Run it]
 
{{trans|C}}
 
<syntaxhighlight>
proc pset x y . .
move x / 4 y / 4
rect 0.25 0.25
.
proc drawline x0 y0 x1 y1 . .
dx = abs (x1 - x0)
sx = -1
if x0 < x1
sx = 1
.
dy = abs (y1 - y0)
sy = -1
if y0 < y1
sy = 1
.
err = -dy div 2
if dx > dy
err = dx div 2
.
repeat
pset x0 y0
until x0 = x1 and y0 = y1
e2 = err
if e2 > -dx
err -= dy
x0 += sx
.
if e2 < dy
err += dx
y0 += sy
.
.
.
drawline 200 10 100 200
drawline 100 200 200 390
drawline 200 390 300 200
drawline 300 200 200 10
</syntaxhighlight>
 
 
=={{header|Elm}}==
 
<langsyntaxhighlight lang="elm">
 
 
Line 1,305 ⟶ 1,580:
bresenhamLineLoop statics error_ (Position x y) positions_
 
</syntaxhighlight>
</lang>
 
=={{header|E}}==
 
{{trans|C}}
 
<lang e>def swap(&left, &right) { # From [[Generic swap]]
def t := left
left := right
right := t
}
 
def drawLine(image, var x0, var y0, var x1, var y1, color) {
def steep := (y1 - y0).abs() > (x1 - x0).abs()
if (steep) {
swap(&x0, &y0)
swap(&x1, &y1)
}
if (x0 > x1) {
swap(&x0, &x1)
swap(&y0, &y1)
}
def deltax := x1 - x0
def deltay := (y1 - y0).abs()
def ystep := if (y0 < y1) { 1 } else { -1 }
var error := deltax // 2
var y := y0
for x in x0..x1 {
if (steep) { image[y, x] := color } else { image[x, y] := color }
error -= deltay
if (error < 0) {
y += ystep
error += deltax
}
}
}</lang>
 
<lang e>def i := makeImage(5, 20)
drawLine(i, 1, 1, 3, 18, makeColor.fromFloat(0,1,1))
i.writePPM(<import:java.io.makeFileOutputStream>(<file:~/Desktop/Bresenham.ppm>))</lang>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
build_path({Sx, Sy}, {Tx, Ty}) ->
if
Line 1,393 ⟶ 1,629:
F2 = F0 + Dx,
through_y({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]).
</syntaxhighlight>
</lang>
OR
<langsyntaxhighlight lang="erlang">
line({X0, Y0}, {X1, Y1}) ->
SX = step(X0, X1),
Line 1,426 ⟶ 1,662:
next_y(Y, _SY, _DX, E, _DE) ->
{Y, E}.
</syntaxhighlight>
</lang>
 
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM BRESENHAM
 
Line 1,461 ⟶ 1,695:
SCREEN(0)
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
 
{{trans|C}}
 
<langsyntaxhighlight lang="euphoria">include std/console.e
include std/graphics.e
include std/math.e
Line 1,581 ⟶ 1,814:
--
--,respectively in the last if check.
--*/</langsyntaxhighlight>
Output:
<pre>
Line 1,603 ⟶ 1,836:
Press Any Key to continue...
</pre>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let inline bresenham fill (x0, y0) (x1, y1) =
let steep = abs(y1 - y0) > abs(x1 - x0)
let x0, y0, x1, y1 =
Line 1,620 ⟶ 1,852:
else
loop (e-dy) (x+1) y
loop (dx/2) x0 y0</langsyntaxhighlight>
The following program tests the above bresenham function by drawing 100 lines into an image and visualizing the result using
{{libheader|Windows Presentation Foundation}}:
<langsyntaxhighlight lang="fsharp">open System.Windows
open System.Windows.Media.Imaging
 
Line 1,639 ⟶ 1,871:
BitmapSource.Create(n, n, 1.0, 1.0, format, null, pixel, n)
Window(Content=image, Title="Bresenham's line algorithm")
|> (Application()).Run |> ignore</langsyntaxhighlight>
=={{header|Factor}}==
A very ugly imperative implementation similar to the wikipedia pseudocode..
<syntaxhighlight lang="factor">USING: accessors arrays kernel locals math math.functions
math.ranges math.vectors rosettacode.raster.display
rosettacode.raster.storage sequences ui.gadgets ;
IN: rosettacode.raster.line
 
:: line-points ( pt1 pt2 -- points )
pt1 first2 :> y0! :> x0!
pt2 first2 :> y1! :> x1!
y1 y0 - abs x1 x0 - abs > :> steep
steep [
y0 x0 y0! x0!
y1 x1 y1! x1!
] when
x0 x1 > [
x0 x1 x0! x1!
y0 y1 y0! y1!
] when
x1 x0 - :> deltax
y1 y0 - abs :> deltay
0 :> current-error!
deltay deltax / abs :> deltaerr
0 :> ystep!
y0 :> y!
y0 y1 < [ 1 ystep! ] [ -1 ystep! ] if
x0 x1 1 <range> [
y steep [ swap ] when 2array
current-error deltaerr + current-error!
current-error 0.5 >= [
ystep y + y!
current-error 1 - current-error!
] when
] { } map-as ;
 
! Needs rosettacode.raster.storage for the set-pixel function and to create the image
: draw-line ( {R,G,B} pt1 pt2 image -- )
[ line-points ] dip
[ set-pixel ] curry with each ;</syntaxhighlight>
=={{header|FBSL}}==
1. In FBSL, successive calls to one and the same subprocedure may be concatenated to a series of argument sets as in Sub Rhombus() below.
Line 1,647 ⟶ 1,917:
 
'''Using pure FBSL's built-in graphics functions:'''
<langsyntaxhighlight lang="qbasic">#DEFINE WM_LBUTTONDOWN 513
#DEFINE WM_CLOSE 16
 
Line 1,681 ⟶ 1,951:
WEND
END SUB
END SUB</langsyntaxhighlight>
'''Output:''' [[File:FBSLBresenham.PNG]]
 
=={{header|Factor}}==
A very ugly imperative implementation similar to the wikipedia pseudocode..
<lang factor>USING: accessors arrays kernel locals math math.functions
math.ranges math.vectors rosettacode.raster.display
rosettacode.raster.storage sequences ui.gadgets ;
IN: rosettacode.raster.line
 
:: line-points ( pt1 pt2 -- points )
pt1 first2 :> y0! :> x0!
pt2 first2 :> y1! :> x1!
y1 y0 - abs x1 x0 - abs > :> steep
steep [
y0 x0 y0! x0!
y1 x1 y1! x1!
] when
x0 x1 > [
x0 x1 x0! x1!
y0 y1 y0! y1!
] when
x1 x0 - :> deltax
y1 y0 - abs :> deltay
0 :> current-error!
deltay deltax / abs :> deltaerr
0 :> ystep!
y0 :> y!
y0 y1 < [ 1 ystep! ] [ -1 ystep! ] if
x0 x1 1 <range> [
y steep [ swap ] when 2array
current-error deltaerr + current-error!
current-error 0.5 >= [
ystep y + y!
current-error 1 - current-error!
] when
] { } map-as ;
 
! Needs rosettacode.raster.storage for the set-pixel function and to create the image
: draw-line ( {R,G,B} pt1 pt2 image -- )
[ line-points ] dip
[ set-pixel ] curry with each ;</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">defer steep \ noop or swap
defer ystep \ 1+ or 1-
 
Line 1,772 ⟶ 2,001:
** *
**
ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{trans|C}}
<langsyntaxhighlight lang="fortran">module RCImagePrimitive
use RCImageBasic
 
Line 1,846 ⟶ 2,074:
end subroutine draw_line
 
end module RCImagePrimitive</langsyntaxhighlight>
 
Usage example:
 
<langsyntaxhighlight lang="fortran">program BasicImageTests
use RCImageBasic
use RCImageIO
Line 1,876 ⟶ 2,104:
call free_img(animage)
 
end program BasicImageTests</langsyntaxhighlight>
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 16-09-2015
' compile with: fbc -s console
' OR compile with: fbc -s gui
Line 1,916 ⟶ 2,144:
Loop Until InKey <> "" ' loop until a key is pressed
 
End</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package raster
 
// Line draws line by Bresenham's algorithm.
Line 1,964 ⟶ 2,191:
func (b *Bitmap) LineRgb(x0, y0, x1, y1 int, c Rgb) {
b.Line(x0, y0, x1, y1, c.Pixel())
}</langsyntaxhighlight>
A demonstration program:
<langsyntaxhighlight lang="go">package main
 
// Files required to build supporting package raster are found in:
Line 1,988 ⟶ 2,215:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">module Bitmap.Line(line) where
 
import Bitmap
Line 2,023 ⟶ 2,249:
deltax = x2 - x1
deltay = abs $ y2 - y1
ystep = if y1 < y2 then 1 else -1</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
 
Using definitions from [[Basic bitmap storage#J|Basic bitmap storage]].
<langsyntaxhighlight lang="j">thru=: <./ + -~ i.@+ _1 ^ > NB. integers from x through y
 
NB.*getBresenhamLine v Returns points for a line given start and end points
Line 2,044 ⟶ 2,269:
NB.*drawLines v Draws lines (x) on image (y)
NB. x is: 2-item list (start and end points) ; (color)
drawLines=: (1&{:: ;~ [: ; [: <@getBresenhamLine"2 (0&{::))@[ setPixels ]</langsyntaxhighlight>
 
'''Example Usage:'''
<langsyntaxhighlight lang="j"> myimg=: 0 255 0 makeRGB 20 32 NB. 32 by 20 green image
myimg=: ((1 1 ,: 5 11) ; 255 0 0 ) drawLines myimg NB. draw red line from xy point 1 1 to 11 5
 
Line 2,055 ⟶ 2,280:
viewRGB myimg=: (Diamond;255 0 0) drawLines myimg NB. draw 4 red lines to form a diamond
viewRGB myimg=: (Square;0 0 255) drawLines myimg NB. draw 4 blue lines to form a square
viewRGB (Diamond;255 0 0) drawLines (Square;0 0 255) drawLines myimg</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
Line 2,172 ⟶ 2,396:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Instead of swaps in the initialisation use error calculation for both directions x and y simultaneously:
<langsyntaxhighlight lang="javascript">function bline(x0, y0, x1, y1) {
 
var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
Line 2,189 ⟶ 2,412:
if (e2 < dy) { err += dx; y0 += sy; }
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
<langsyntaxhighlight Julialang="julia">function drawline!(img::Matrix{T}, x0::Int, y0::Int, x1::Int, y1::Int, col::T) where T
δx = abs(x1 - x0)
δy = abs(y1 - y0)
Line 2,219 ⟶ 2,441:
drawline!(img, 1, 1, 5, 5, Gray(0.0));
println("\nModified image:")
display(img); println()</langsyntaxhighlight>
 
{{out}}
Line 2,239 ⟶ 2,461:
Gray{Float64}(255.0) Gray{Float64}(255.0) Gray{Float64}(255.0) Gray{Float64}(255.0) Gray{Float64}(0.0) </pre>
 
=={{header|Korn Shellksh}}==
<syntaxhighlight lang="ksh">function line {
typeset x0=$1 y0=$2 x1=$3 y1=$4
 
if ((x0 > x1))
<lang>function line {
x0=$1; y0=$2 x1=$3; y1=$4
 
if (( x0 > x1 ))
then
((dx = x0 - x1)); ((sx = -1))
Line 2,251 ⟶ 2,472:
fi
 
if (( y0 > y1 ))
then
((dy = y0 - y1)); ((sy = -1))
Line 2,258 ⟶ 2,479:
fi
 
if (( dx > dy ))
then
((err = dx))
Line 2,266 ⟶ 2,487:
((err /= 2)); ((e2 = 0))
 
while /bin/true:
do
echo $x0 $y0
(( x0 == x1 && y0 == y1 )) && return
((e2 = err))
(( e2 > -dx)) && { ((err -= dy )); (( x0 += sx )) }
(( e2 < dy)) && { ((err += dx )); (( y0 += sy )) }
 
done
}</langsyntaxhighlight>
Output from the statement:
 
Output from the statement:-
line 0 0 3 4
(which could be piped to another program)
<langpre>0 0
1 1
1 2
2 3
3 4</langpre>
 
=={{header|KotlinLua}}==
{{trans|JavaC}}
{{works with|Lua 5.1 (or above, tested on: 5.1.5, 5.2.3, 5.3.5)}}
<lang scala>// version 1.1.2
<syntaxhighlight lang="lua">
 
-----------------------------------------------
import java.awt.*
-- Bitmap replacement
import javax.swing.*
-- (why? current Lua impl lacks a "set" method)
 
-----------------------------------------------
class Bresenham(w: Int, h: Int) : JPanel() {
local Bitmap = {
private val centerX = w / 2
new = function(self, width, height)
private val centerY = h / 2
local instance = setmetatable({ width=width, height=height }, self)
 
instance:alloc()
init {
return instance
preferredSize = Dimension(w, h)
end,
background = Color.blue
alloc = function(self)
}
self.pixels = {}
 
for y = 1, self.height do
override fun paintComponent(g: Graphics) {
self.pixels[y] = {}
super.paintComponent(g)
for x drawLine(g,= 01, 0, 8, 19) //self.width NNEdo
drawLine(g,self.pixels[y][x] 0,= 0, 19, 8) // ENE0x00000000
end
drawLine(g, 0, 0, 19, -8) // ESE
end
drawLine(g, 0, 0, 8, -19) // SSE
end,
drawLine(g, 0, 0, -8, -19) // SSW
clear = function(self, c)
drawLine(g, 0, 0, -19, -8) // WSW
for y = drawLine(g1, 0, 0, -19, 8) //self.height WNWdo
for x drawLine(g,= 01, 0, -8, 19) //self.width NNWdo
self.pixels[y][x] = c or 0x00000000
}
end
 
end
private fun plot(g: Graphics, x: Int, y: Int) {
end,
g.color = Color.white
get = function(self, x, y)
g.drawOval(centerX + x * 10, centerY -y * 10, 10, 10)
x, y = math.floor(x+1), math.floor(y+1)
}
if ((x>=1) and (x<=self.width) and (y>=1) and (y<=self.height)) then
 
return self.pixels[y][x]
private fun drawLine(g: Graphics, x1: Int, y1: Int, x2: Int, y2: Int) {
var d = 0else
return nil
val dy = Math.abs(y2 - y1)
end
val dx = Math.abs(x2 - x1)
end,
val dy2 = dy shl 1
set = function(self, x, y, c)
val dx2 = dx shl 1
x, val ixy = if math.floor(x1 < x2x+1), 1 else -math.floor(y+1)
if ((x>=1) and (x<=self.width) and (y>=1) and (y<=self.height)) then
val iy = if (y1 < y2) 1 else -1
self.pixels[y][x] = varc xx =or x10x00000000
var yy = y1end
end,
 
if (dy <= dx) {
while (true) {
plot(g, xx, yy)
if (xx == x2) break
xx += ix
d += dy2
if (d > dx) {
yy += iy
d -= dx2
}
}
}
else {
while (true) {
plot(g, xx, yy)
if (yy == y2) break
yy += iy
d += dx2
if (d > dy) {
xx += ix
d -= dy2
}
}
}
}
}
Bitmap.__index = Bitmap
setmetatable(Bitmap, { __call = function (t, ...) return t:new(...) end })
 
------------------------------
fun main(args: Array<String>) {
-- Bresenham's Line Algorithm:
SwingUtilities.invokeLater {
------------------------------
val f = JFrame()
Bitmap.line = function(self, x1, y1, x2, y2, c)
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
local dx, sx = math.abs(x2-x1), x1<x2 and 1 or -1
f.isVisible = true
local dy, sy = math.abs(y2-y1), y1<y2 and 1 or -1
f.add(Bresenham(600, 500), BorderLayout.CENTER)
local err = math.floor((dx>dy and dx or -dy)/2)
f.title = "Bresenham"
while(true) do
f.isResizable = false
self:set(x1, y1, c or f.pack(0xFFFFFFFF)
if (x1==x2 and y1==y2) then break end
f.setLocationRelativeTo(null)
if (err > -dx) then
}
err, x1 = err-dy, x1+sx
}</lang>
if (x1==x2 and y1==y2) then
self:set(x1, y1, c or 0xFFFFFFFF)
break
end
end
if (err < dy) then
err, y1 = err+dx, y1+sy
end
end
end
 
--------
-- Demo:
--------
Bitmap.render = function(self, charmap)
for y = 1, self.height do
local rowtab = {}
for x = 1, self.width do
rowtab[x] = charmap[self.pixels[y][x]]
end
print(table.concat(rowtab))
end
end
local bitmap = Bitmap(61,21)
bitmap:clear()
bitmap:line(0,10,30,0)
bitmap:line(30,0,60,10)
bitmap:line(60,10,30,20)
bitmap:line(30,20,0,10)
bitmap:render({[0x000000]='.', [0xFFFFFFFF]='X'})</syntaxhighlight>
{{out}}<pre>.............................XXX.............................
..........................XXX...XXX..........................
.......................XXX.........XXX.......................
....................XXX...............XXX....................
.................XXX.....................XXX.................
..............XXX...........................XXX..............
...........XXX.................................XXX...........
........XXX.......................................XXX........
.....XXX.............................................XXX.....
..XXX...................................................XXX..
XX.........................................................XX
..XXX...................................................XXX..
.....XXX.............................................XXX.....
........XXX.......................................XXX........
...........XXX.................................XXX...........
..............XXX...........................XXX..............
.................XXX.....................XXX.................
....................XXX...............XXX....................
.......................XXX.........XXX.......................
..........................XXX...XXX..........................
.............................XXX.............................
</pre>
=={{header|Maple}}==
 
<langsyntaxhighlight lang="maple">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;
Line 2,407 ⟶ 2,654:
end do;
return img2;
end proc:</langsyntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
<syntaxhighlight lang="mathematica">Rasterize[Style[Graphics[Line[{{0, 0}, {20, 10}}]], Antialiasing -> False]]</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
 
<lang Mathematica>Rasterize[ Style[Graphics[Line[{{0, 0}, {20, 10}}]], Antialiasing -> False]]
</lang>
 
=={{header|MATLAB}}==
Note: Store this function in a file named "bresenhamLine.m" in the @Bitmap folder for the Bitmap class defined [[Bitmap#MATLAB|here]].
[[File:Bresenham.png|thumb|MATLAB sample usage output.]]
<syntaxhighlight lang="matlab">
<lang MATLAB>
%screen = Bitmap object
%startPoint = [x0,y0]
Line 2,479 ⟶ 2,722:
assignin('caller',inputname(1),screen); %saves the changes to the object
end
</syntaxhighlight>
</lang>
 
Sample Usage:
<syntaxhighlight lang="matlab">
<lang MATLAB>
>> img = Bitmap(800,600);
>> img.bresenhamLine([400 550],[200 400],[255 255 255]);
Line 2,491 ⟶ 2,734:
>> img.bresenhamLine([400 550],[400 150],[255 255 255]);
>> disp(img)
</syntaxhighlight>
</lang>
 
=={{header|MAXScript}}==
 
<langsyntaxhighlight lang="maxscript">fn plot img coord steep col =
(
if steep then
Line 2,546 ⟶ 2,788:
myBitmap = bitmap 512 512 color:(color 0 0 0)
myBitmap = drawLine myBitmap [0, 511] [511, 0] #((color 255 255 255))
display myBitmap</langsyntaxhighlight>
 
=={{header|Metal}}==
 
For drawing lines between points in an Apple Metal compute shader.
 
<langsyntaxhighlight lang="metal">void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end);
 
void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end)
Line 2,590 ⟶ 2,831:
}
}
}</langsyntaxhighlight>
 
=={{header|MiniScript}}==
This GUI implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<syntaxhighlight lang="miniscript">
drawLine = function(img, x0, y0, x1, y1, colr)
sign = function(a, b)
if a < b then return 1
return -1
end function
dx = abs(x1 - x0)
sx = sign(x0, x1)
dy = abs(y1 - y0)
sy = sign(y0, y1)
if dx > dy then
err = dx
else
err = -dy
end if
err = floor(err / 2)
while true
img.setPixel x0, y0, colr
if x0 == x1 and y0 == y1 then break
e2 = err
if e2 > -dx then
err -= dy
x0 += sx
end if
if e2 < dy then
err += dx
y0 += sy
end if
end while
end function
 
img= Image.create(320, 320)
drawLine img, 0, 0, 250, 300, color.red
gfx.clear
gfx.drawImage img, 0, 0
</syntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import mathbitmap
 
proc linedrawLine*(img: var Image,; p, q: Point; color: Color) =
let
dx = abs(q.x - p.x)
Line 2,609 ⟶ 2,893:
 
while true:
img[p.x, p.y] = Blackcolor
if p == q:
break
Line 2,618 ⟶ 2,902:
if e2 < dy:
err += dx
p.y += sy</lang>
 
when isMainModule:
var img = newImage(16, 16)
img.fill(White)
img.drawLine((0, 7), (7, 15), Black)
img.drawLine((7, 15), (15, 7), Black)
img.drawLine((15, 7), (7, 0), Black)
img.drawLine((7, 0), (0, 7), Black)
img.print()</syntaxhighlight>
 
{{out}}
<pre>.......H........
......H.H.......
.....H...H......
....H.....H.....
...H.......HH...
..H..........H..
.H............H.
H..............H
.H............H.
..H..........H..
...H........H...
...H.......H....
....H.....H.....
.....H...H......
......H.H.......
.......H........</pre>
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let draw_line ~img ~color ~p0:(x0,y0) ~p1:(x1,y1) =
 
let steep = abs(y1 - y0) > abs(x1 - x0) in
Line 2,661 ⟶ 2,971:
in
loop x0 y0 error
;;</langsyntaxhighlight>
 
=={{header|Pascal}}==
 
[[Bresenham's_line_algorithm#Delphi | Delphi]]
 
=={{header|Perl}}==
 
{{libheader|Imlib2}}
 
<langsyntaxhighlight lang="perl">#! /usr/bin/perl
use strict;
use Image::Imlib2;
Line 2,733 ⟶ 3,041:
$img->save("test1.png");
 
exit 0;</langsyntaxhighlight>
 
Images <tt>test0.png</tt> and <tt>test1.png</tt> look different since Imlib2 draw lines with antialiasing.
 
=={{header|Perl 6}}==
{{works with|Rakudo|2018.03}}
Bitmap class from [[Bitmap#Perl_6|Bitmap]] task.
<lang perl6>class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @!data;
method fill(Pixel $p) {
@!data = $p.clone xx ($!width*$!height)
}
method pixel(
$i where ^$!width,
$j where ^$!height
--> Pixel
) is rw { @!data[$i + $j * $!width] }
method set-pixel ($i, $j, Pixel $p) {
self.pixel($i, $j) = $p.clone;
}
method get-pixel ($i, $j) returns Pixel {
self.pixel($i, $j);
}
}
sub line(Bitmap $bitmap, $x0 is copy, $x1 is copy, $y0 is copy, $y1 is copy) {
my $steep = abs($y1 - $y0) > abs($x1 - $x0);
if $steep {
($x0, $y0) = ($y0, $x0);
($x1, $y1) = ($y1, $x1);
}
if $x0 > $x1 {
($x0, $x1) = ($x1, $x0);
($y0, $y1) = ($y1, $y0);
}
my $Δx = $x1 - $x0;
my $Δy = abs($y1 - $y0);
my $error = 0;
my $Δerror = $Δy / $Δx;
my $y-step = $y0 < $y1 ?? 1 !! -1;
my $y = $y0;
for $x0 .. $x1 -> $x {
my $pix = Pixel.new(R => 100, G => 200, B => 0);
if $steep {
$bitmap.set-pixel($y, $x, $pix);
} else {
$bitmap.set-pixel($x, $y, $pix);
}
$error += $Δerror;
if $error >= 0.5 {
$y += $y-step;
$error -= 1.0;
}
}
}</lang>
 
=={{header|Phix}}==
Modified copy of [[Bitmap/Bresenham%27s_line_algorithm#Euphoria|Euphoria]], with a bigger bitmap and a simpler pattern.
Requires new_image() from [[Bitmap#Phix|Bitmap]], write_ppm() from [[Bitmap/Write_a_PPM_file#Phix|Write_a_PPM_file]]. <br>
IncludedNote asthat demo\rosetta\Bresenham_line.exw is just the last 6 lines below preceded by include ppm.e since that contains bresLine() which is also used by several other examples, resultsand covers the above requirements, as shown commented out. Results may be verified with demo\rosetta\viewppm.exw
<syntaxhighlight lang="phix">-- demo\rosetta\Bresenham_line.exw (runnable version)
<lang Phix>function bresLine(sequence screenData, integer x0, integer y0, integer x1, integer y1, integer colour)
-- The line algorithm
integer deltaX = abs(x1-x0),
deltaY = abs(y1-y0),
stepX = iff(x0<x1,1,-1),
stepY = iff(y0<y1,1,-1),
lineError = iff(deltaX>deltaY,deltaX,-deltaY),
prevle
 
global function bresLine(sequence image, integer x0, y0, x1, y1, colour)
lineError = round(lineError/2,1)
while-- 1The doline algorithm
integer dimx if x0>=1 and x0<=length(screenDataimage),
and y0>=1 and y0< dimy = length(screenDataimage[x01]) then,
screenData[x0][y0]deltaX = colourabs(x1-x0),
deltaY = abs(y1-y0),
stepX = iff(x0<x1,1,-1),
stepY = iff(y0<y1,1,-1),
lineError = iff(deltaX>deltaY,deltaX,-deltaY),
prevle
lineError = round(lineError/2, 1)
while true do
if x0>=1 and x0<=dimx
and y0>=1 and y0<=dimy then
image[x0][y0] = colour
end if
if x0=x1 and y0=y1 then exit end if
Line 2,823 ⟶ 3,077:
end if
end while
return screenDataimage
end function
 
--include ppm.e -- red, green, blue, white, new_image(), write_ppm(), bresLine() (as distributed, instead of the above)
sequence screenData = new_image(400,300,black)
screenData = bresLine(screenData,100,1,50,300,red)
screenData = bresLine(screenData,1,180,400,240,green)
screenData = bresLine(screenData,200,1,400,150,white)
screenData = bresLine(screenData,195,1,205,300,blue)
write_ppm("bresenham.ppm",screenData)</lang>
 
sequence screenData = new_image(400,300,black)
screenData = bresLine(screenData,100,1,50,300,red)
screenData = bresLine(screenData,1,180,400,240,green)
screenData = bresLine(screenData,200,1,400,150,white)
screenData = bresLine(screenData,195,1,205,300,blue)
write_ppm("bresenham.ppm",screenData)</syntaxhighlight>
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de brez (Img X Y DX DY)
(let SX
(cond
Line 2,872 ⟶ 3,127:
(prinl "P1")
(prinl 120 " " 90)
(mapc prinl Img) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
===version 1===
{{incorrect|PL/I|The sample output does not start at -1/-3!?! Pls show the complete program producing this output.}}
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Draw a line from (x0, y0) to (x1, y1). 13 May 2010 */
/* Based on Rosetta code proforma. */
Line 2,914 ⟶ 3,168:
 
end draw_line;
</syntaxhighlight>
</lang>
 
Output from the statement:-
call draw_line(-1, -3, 6, 10);
for a -10:10 x -10:10 grid:
<syntaxhighlight lang="text">
..........|..........
..........|..........
Line 2,941 ⟶ 3,195:
..........|..........
..........|..........
</syntaxhighlight>
</lang>
 
===version 2===
<langsyntaxhighlight PLlang="pl/Ii">*process source xref or(!);
brbn:Proc Options(main);
/*********************************************************************
Line 2,994 ⟶ 3,248:
image(x0,y0)='X';
end;
end;</langsyntaxhighlight>
'''output'''
<pre>11 ..|.......
Line 3,013 ⟶ 3,267:
-4 ..|.......
2101234567</pre>
 
=={{header|Prolog}}==
Works with SWI-prolog.
 
<lang Prolog>
use_module(library(pce)).
lindraw(X1,Y1,X2,Y2):-
new(Win,window("Line")),
new(Pix,pixmap(@nil,black,white,X2+30,Y2+30)),
send(Win,size,size(400,400)),
draw_line(Pix,X1,Y1,X2,Y2),
new(Bmp,bitmap(Pix)),
send(Win,display,Bmp,point(0,0)),
send(Win,open).
 
<syntaxhighlight lang="prolog">
draw_recursive_line(_Pict,X,X,_DX,_DY,Y,Y,_D,_Sx,_Sy).%Don't iterate if X and X2 are the same number
:- use_module(bitmap).
draw_recursive_line(Pict,X,X2,DX,DY,Y,Y2,C,Sx,Sy):-
:- use_module(bitmapIO).
( C>0->%If the difference is greater than one, add Y one to Y.
:- use_module(library(clpfd)).
Y1 is Y+Sy,
 
send(Pict,pixel(X,Y1,colour(black))),
% ends when X1 = X2 and Y1 = Y2
C2 is C+(2*DY-2*DX);
draw_recursive_line(NPict,Pict,Color,X,X,_DX,_DY,Y,Y,_E,_Sx,_Sy):-
Y1 is Y,
sendset_pixel0(NPict,Pict,pixel([X,Y],colour(blackColor))),.
draw_recursive_line(NPict,Pict,Color,X,X2,DX,DY,Y,Y2,E,Sx,Sy):-
C2 is C+(2*DY)),
set_pixel0(TPict,Pict,[X,Y],Color),
X0 is X+Sx,%The next iteration
E2 #= 2*E,
draw_recursive_line(Pict,X0,X2,DX,DY,Y1,Y2,C2,Sx,Sy).
% because we can't accumulate error we set Ey or Ex to 1 or 0
isneg(X,O):-
% depending on whether we need to add dY or dX to the error term
( X<0->
( E2 >= DY ->
Ey = 1, NX #= X + Sx;
Ey = 0, NX = X),
( E2 =< DX ->
Ex = 1, NY #= Y + Sy;
Ex = 0, NY = Y),
NE #= E + DX*Ex + DY*Ey,
draw_recursive_line(NPict,TPict,Color,NX,X2,DX,DY,NY,Y2,NE,Sx,Sy).
 
draw_line(NPict,Pict,Color,X1,Y1,X2,Y2):-
O is -1;
DeltaY #= Y2-Y1,
( X\==0->
DeltaX #= X2-X1,
O is 1;
( DeltaY < 0 -> Sy = -1; Sy = 1),
O is 0)).
( DeltaX < 0 -> Sx = -1; Sx = 1),
DX #= abs(DeltaX),
DY #= -1*abs(DeltaY),
E #= DY+DX,
draw_recursive_line(NPict,Pict,Color,X1,X2,DX,DY,Y1,Y2,E,Sx,Sy).
 
draw_line(Pict,X1,Y1,X2,Y2):-
DY is abs(Y2-Y1),
DX is abs(X2-X1),
isneg(DX,Sx),
isneg(DY,Sy),
D = 2*DY-DX,%The slope of the line
draw_recursive_line(Pict,X1,X2,DX,DY,Y1,Y2,D,Sx,Sy).
</lang>
 
init:-
new_bitmap(B,[100,100],[255,255,255]),
draw_line(NB,B,[0,0,0],2,2,10,90),
write_ppm_p6('line.ppm',NB).
</syntaxhighlight>
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure BresenhamLine(x0 ,y0 ,x1 ,y1)
If Abs(y1 - y0) > Abs(x1 - x0);
steep =#True
Line 3,115 ⟶ 3,367:
Until Event = #PB_Event_CloseWindow
EndIf
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|3.1}}
Line 3,122 ⟶ 3,373:
Extending the example given [[Basic_bitmap_storage/Python#Alternative_version|here]] and using the algorithm from the Ada solution:
 
<langsyntaxhighlight lang="python">def line(self, x0, y0, x1, y1):
"Bresenham's line algorithm"
dx = abs(x1 - x0)
Line 3,179 ⟶ 3,430:
| |
+-----------------+
'''</langsyntaxhighlight>
 
===Not relying on floats===
Extending the example given [[Basic_bitmap_storage/Python#Alternative_version|here]].
 
<langsyntaxhighlight lang="python">
from fractions import Fraction
 
Line 3,201 ⟶ 3,452:
 
# see test code above
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Port of the Python version.
<langsyntaxhighlight lang="racket">
#lang racket
(require racket/draw)
Line 3,239 ⟶ 3,489:
(apply draw-line (cons dc points)))
bm
</syntaxhighlight>
</lang>
=={{header|Raku}}==
 
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
Bitmap class from [[Bitmap#Raku|Bitmap]] task.
<syntaxhighlight lang="raku" line>class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @!data;
method fill(Pixel $p) {
@!data = $p.clone xx ($!width*$!height)
}
method pixel(
$i where ^$!width,
$j where ^$!height
--> Pixel
) is rw { @!data[$i + $j * $!width] }
method set-pixel ($i, $j, Pixel $p) {
self.pixel($i, $j) = $p.clone;
}
method get-pixel ($i, $j) returns Pixel {
self.pixel($i, $j);
}
}
sub line(Bitmap $bitmap, $x0 is copy, $x1 is copy, $y0 is copy, $y1 is copy) {
my $steep = abs($y1 - $y0) > abs($x1 - $x0);
if $steep {
($x0, $y0) = ($y0, $x0);
($x1, $y1) = ($y1, $x1);
}
if $x0 > $x1 {
($x0, $x1) = ($x1, $x0);
($y0, $y1) = ($y1, $y0);
}
my $Δx = $x1 - $x0;
my $Δy = abs($y1 - $y0);
my $error = 0;
my $Δerror = $Δy / $Δx;
my $y-step = $y0 < $y1 ?? 1 !! -1;
my $y = $y0;
for $x0 .. $x1 -> $x {
my $pix = Pixel.new(R => 100, G => 200, B => 0);
if $steep {
$bitmap.set-pixel($y, $x, $pix);
} else {
$bitmap.set-pixel($x, $y, $pix);
}
$error += $Δerror;
if $error >= 0.5 {
$y += $y-step;
$error -= 1.0;
}
}
}</syntaxhighlight>
=={{header|RapidQ}}==
 
Use this routine together with the code from [[Basic_bitmap_storage#RapidQ|Basic bitmap storage]] to create a full application.
 
<langsyntaxhighlight lang="rapidq">SUB draw_line(x1, y1, x2, y2, colour)
x_dist = abs(x2-x1)
y_dist = abs(y2-y1)
Line 3,279 ⟶ 3,584:
END IF
END SUB</langsyntaxhighlight>
 
Example usage:
 
<langsyntaxhighlight lang="rapidq">SUB PaintCanvas
draw_line 200, 10, 100, 200, &H00ff00
draw_line 100, 200, 200, 400, &H00ff00
draw_line 200, 400, 300, 200, &H00ff00
draw_line 300, 200, 200, 10, &H00ff00
END SUB</langsyntaxhighlight>
 
=={{header|REXX}}==
=== version 1 ===
This REXX version has automatic scaling (for displaying the plot), &nbsp; includes a border, &nbsp; accepts lines segments from the
border, &nbsp; accepts lines segments from the
<br>command line, &nbsp; displays a (background) plot field, &nbsp; and it also handles multiple line segments.
<br>command line, &nbsp; displays a (background) plot field, &nbsp; uses an infinite field, &nbsp; and
<lang rexx>/*REXX program plots/draws line segments using the Bresenham's line (2D) algorithm. */
it also handles multiple line segments.
<syntaxhighlight lang="rexx">/*REXX program plots/draws line segments using the Bresenham's line (2D) algorithm. */
parse arg data /*obtain optional arguments from the CL*/
if data='' then data= "(1,8) (8,16) (16,8) (8,1) (1,8)" /* ◄──── a rhombus.*/
data= translate(data, , '()[]{}/,:;') /*elide chaff from the data points. */
@.= '·' /*filluse themid─dots arraychars with(plot middle─dots charsbackground).*/
do points=1 while data\='' /*put the data points into an array (!)*/
parse var data x y data; !.points=x y /*extract the line segments. */
if points==1 then do; minX= x; maxX= x; minY= y; maxY= y; end /*1st case.*/
end
minX=min(minX,x); maxX=max(maxX,x); minY=min(minY,y); maxY=max(maxY,y)
minX= min(minX,x); maxX= max(maxX,x); minY= min(minY,y); maxY= max(maxY,y)
end /*points*/ /* [↑] data points pairs in array !. */
border=2 end /*points*/ /* [↑] data /*border: points ispairs extrain spacearray around plot!. */
minX=minX-border*= 2; maxX=maxX+border*2 /*min and max X for the plot display /*border: is extra space around plot. */
minYminX=minY minX - border *2; maxYmaxX=maxY+border maxX + border*2 /*min " " " Y " " " and max X " for the plot display.*/
minY= minY - border ; maxY= domaxY x=minX+ border to maxX; @.x.0='─';/* " end " " Y " " /*draw a" dash from " left ───► right.*/
 
do y=minY to maxY; @.0.y='│'; end /*draw a pipe from lowest ───► highest*/
@.0.0='┼' do x=minX to maxX; @.x.0= '─'; end /*draw a dash from left ───► /*define the plot's origin axis pointright. */
do segy=2minY to points-1maxY; _@.0.y=seg-1 '│'; end /*obtain thedraw a Xpipe andfrom Y lowest line───► coördinateshighest*/
@.0.0= '┼' call draw_line !._, !.seg /*draw (plot) a line segment. /*define the plot's origin axis point. */
end do /*seg*/ =2 to points-1; _= seg - 1 /* [↑] drawingobtain the line segments.X and Y line coördinates*/
call drawLine !._, !.seg /*draw (plot) a line segment. */
end /*seg*/ /* [↑] drawing the line segments. */
/* [↓] display the plot to terminal. */
do y=maxY to minY by -1; _= /*display the plot one line at a time. */
do x=minX to maxX; _= _ || @.x.y /*construct/build a line of the plot. */
end /*x*/ /* (a line is a "row" of points.) */
say _ /*display a line of the plot──►terminal*/
end /*y*/ /* [↑] all done plotting the points. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
draw_linedrawLine: procedure expose @.; parse arg x y,xf yf; parse value '-1 -1' with plotChar='Θ'sx sy
dx= abs(xf-x); if x<xf then sx= +1 /*obtain X range, determine the slope*/
dy= abs(yf-y); if y<yf then else sxsy= -1 /* " Y /* " " " negative slope. " */
dy err=abs(yf dx -y); dy if y<yf then sy= +1 /*obtain Y range, determine the slope/*calculate error between adjustments. */
else sy= -1 /* /*Θ is the plot character for negative slopepoints. */
err=dx-dy do forever; @.x.y= 'Θ' /*plot the points until it's /*calculate error between adjustmentscomplete. */
do forever; if @.x.=xf & y=plotCharyf then return /*plotare the plot points untilat the finish? it's complete. */
if x=xf & y err2=yf err + err then return /*are thecalculate plot pointsdouble at the finish?error value. */
err2=err+err if err2 > -dy then do; err= err - dy; x= x + sx; /*addition is faster than: err*2. */end
if err2 >< -dy dx then do; err= err-dy + dx; x y=x y +sx sy; end
if err2 < dxend then do; err=err+dx; y=y+sy; end/*forever*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
end /*forever*/</lang>
'''output''' &nbsp; when using the default input:
<pre>
···│····················
Line 3,357 ⟶ 3,664:
</pre>
 
=== version 2 ===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 21.05.2014 Walter Pachl
* Implementing the pseudo code of
Line 3,401 ⟶ 3,708:
end
end
Return</langsyntaxhighlight>
'''output'''
<pre>11 ..|.......
Line 3,420 ⟶ 3,727:
-4 ..|.......
2101234567</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "guilib.ring"
load "stdlib.ring"
Line 3,479 ⟶ 3,785:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
Output :
[https://lh3.googleusercontent.com/-6uJvON0dAuo/V2LO2zz4zQI/AAAAAAAAALE/IjEGFuhta6oUSeG2QfuxcPBWMmCyNCjdwCLcB/s1600/CalmoSoftBresenham.jpg Bitmap/Bresenham's algorithm]
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">Pixel = Struct.new(:x, :y)
 
class Pixmap
Line 3,531 ⟶ 3,836:
bitmap.draw_line(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW)
end
bitmap.draw_line(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW)</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
<lang Rust>
struct Point {
x: i32,
Line 3,541 ⟶ 3,845:
 
fn main() {
let resultmut points: Vec<Point> = get_coordinatesVec::new(1, 1, 69, 28);
points.append(&mut get_coordinates(1, 20, 20, 28));
draw_line(result, 70, 30);
points.append(&mut get_coordinates(20, 28, 69, 0));
draw_line(points, 70, 30);
}
 
fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<Point> {
let mut coordinates: Vec<Point> = vec![];
let dx:i32 = i32::abs(x2 - x1);
let dy:i32 = i32::abs(y2 - y1);
let sx:i32 = { if x1 < x2 { 1 } else { -1 } };
let sy:i32 = { if x1y1 < x2y2 { 1 } else { -1 } };
 
1
let mut error:i32 = (if dx > dy { dx } else { -dy }) / 2 ;
-1
}
};
let sy:i32 ={
if y1 < y2 {
1
} else {
-1
}
};
let mut error:i32 = dx - dy;
let mut current_x:i32 = x1;
let mut current_y:i32 = y1;
loop {
coordinates.push(Point { x: current_x, y: current_y });
coordinates.push(Point { x : current_x, y: current_y });
while current_x != x2 && current_y != y2 {
 
let error2:i32 = 2 * error;
if error2current_x >== i32::abs(dy)x2 && current_y == y2 { break; }
 
let error2:i32 = error;
 
if error2 > -dx {
error -= dy;
current_x += sx;
}
coordinates.push(Point { x: current_x, y: current_y });
} else if error2 <= i32::abs(dx)dy {
error += dx;
current_y += sy;
coordinates.push(Point { x: current_x, y: current_y });
}
}
Line 3,587 ⟶ 3,885:
let is_point_in_line = line.iter().any(| point| point.x == row && point.y == col);
match is_point_in_line {
true => print!("@"),
_ => {print!(".")
if col == 0 || col == (height - 1) || row == 0 || row == (width - 1) {
print!("☗");
} else {
print!(".");
}
}
};
}
Line 3,600 ⟶ 3,892:
}
}
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
.....................................................................@
☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗
☗❖❖❖...................................................................@@.
..❖❖❖...............................................................@@...
....❖❖❖❖...........................................................@@.....
.......❖❖❖.......................................................@.......
.........❖❖❖❖...................................................@@........
............❖❖❖..............................................@@..........
..............❖❖❖❖..........................................@@............
.................❖❖❖......................................@..............
...................❖❖❖❖..................................@@...............
......................❖❖❖.............................@@.................
........................❖❖❖❖.........................@@...................
...........................❖❖❖.....................@.....................
.............................❖❖❖❖.................@@......................
................................❖❖❖............@@........................
..................................❖❖❖❖........@@..........................
.....................................❖❖❖....@............................
.......................................❖❖❖❖@@.............................
.....................................@@........❖❖❖.......................
...................................@@.............❖❖❖❖....................
.@@...............................@.................❖❖❖..................
...@@...........................@@.....................❖❖❖❖...............
.....@@.......................@@.........................❖❖❖.............
.......@@@..................@@..............................❖❖❖❖..........
..........@@...............@..................................❖❖❖........
............@@@..........@@......................................❖❖❖❖.....
...............@@......@@..........................................❖❖❖...
.................@@..@@...............................................❖❖❖❖☗
...................@@.................................................❖☗
......................................................................
☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗☗
</pre>
 
=={{header|Scala}}==
Uses the [[Basic_bitmap_storage#Scala|Scala Basic Bitmap Storage]] class.
<langsyntaxhighlight lang="scala">object BitmapOps {
def bresenham(bm:RgbBitmap, x0:Int, y0:Int, x1:Int, y1:Int, c:Color)={
val dx=math.abs(x1-x0)
Line 3,660 ⟶ 3,951:
bm.setPixel(x, y, c)
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func my_draw_line(img, x0, y0, x1, y1) {
 
var steep = (abs(y1 - y0) > abs(x1 - x0))
Line 3,716 ⟶ 4,006:
img.draw_line(80, 10, 10, 80)
 
img.save("test1.png")</langsyntaxhighlight>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "DrawLine" )
@( description, "Draw a line given 2 points with the Bresenham's algorithm." )
@( see_also, "http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure drawline is
 
-- Spar 1.x has only single-dimensional arrays but we can simulate a
-- two dimensional array that has been folded into a 1D array
 
width : constant positive := 20;
height : constant positive := 20;
type image_array is array(1..400) of character;
Picture : image_array;
 
-- Line
-- Draw a line between two coordinates using the given character
 
procedure Line ( Start_X : positive; Start_Y : positive; Stop_X : positive; Stop_Y : positive; Color : character) is
 
-- at this point, formal parameters are defined but the actual values aren't defined!
-- but creating a dummy Line in a test script works?
 
DX : constant float := abs( float( Stop_X ) - float( Start_X ) );
DY : constant float := abs( float( Stop_Y ) - float( Start_Y ) );
Err : float;
X : positive := Start_X;
Y : positive := Start_Y;
Step_X : integer := 1;
Step_Y : integer := 1;
begin
if Start_X > Stop_X then
Step_X := -1;
end if;
if Start_Y > Stop_Y then
Step_Y := -1;
end if;
if DX > DY then
Err := DX / 2.0;
while X /= Stop_X loop
Picture (X + width*(Y-1)) := Color;
Err := @ - DY;
if Err < 0.0 then
Y := positive( integer(@) + Step_Y);
Err := @ + DX;
end if;
X := positive( integer(@) + Step_X );
end loop;
else
Err := DY / 2.0;
while Y /= Stop_Y loop
Picture (X + height*(Y-1)) := Color;
Err := @ - DX;
if Err < 0.0 then
X := positive( integer(@) + Step_X );
Err := @ + DY;
end if;
Y := positive( integer(@) + Step_Y );
end loop;
end if;
Picture (X + width*(Y-1)) := Color;
end Line;
 
-- new_picture
-- Erase the picture by filling it with spaces.
 
procedure new_picture is
begin
for i in arrays.first( Picture )..arrays.last( Picture ) loop
Picture(i) := ' ';
end loop;
end new_picture;
 
-- render
-- Draw the contents of the picture area.
 
procedure render is
begin
for i in arrays.first( Picture )..arrays.last( Picture ) loop
put( Picture(i) );
if i mod width = 0 then
new_line;
end if;
end loop;
end render;
 
begin
new_picture;
Line( 1, 8, 8, 16, 'X' );
Line( 8,16,16, 8, 'X' );
Line(16, 8, 8, 1, 'X' );
Line( 8, 1, 1, 8, 'X' );
render;
end drawline;</syntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
ref [[Basic bitmap storage#Tcl]]
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk
 
Line 3,759 ⟶ 4,150:
fill $img black
drawLine $img yellow {20 20} {180 80}
drawLine $img yellow {180 20} {20 80}</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
Line 3,767 ⟶ 4,157:
{{trans|E}}
 
<langsyntaxhighlight lang="ti89b">(lx0, ly0, lx1, ly1)
Prgm
Local steep, x, y, dx, dy, ystep, error, tmp
Line 3,800 ⟶ 4,190:
EndIf
EndFor
EndPrgm</langsyntaxhighlight>
 
=={{header|VBScript}}==
{{trans|Rexx}}
<langsyntaxhighlight lang="vb">'Bitmap/Bresenham's line algorithm - VBScript - 13/05/2019
Dim map(48,40), list(10), ox, oy
data=Array(1,8, 8,16, 16,8, 8,1, 1,8)
Line 3,856 ⟶ 4,245:
If err2< dx Then err=err+dx: y=y+sy
Loop
End Sub 'draw_line </langsyntaxhighlight>
{{out}}
<pre>
Line 3,880 ⟶ 4,269:
...|....................
</pre>
 
 
 
=={{header|Vedit macro language}}==
 
<langsyntaxhighlight lang="vedit">// Daw a line using Bresenham's line algorithm.
// #1=x1, #2=y1; #3=x2, #4=y2
 
Line 3,923 ⟶ 4,309:
}
Num_Pop(31,35)
return</langsyntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart"># doesn't handle vertical lines
def (line x0 y0 x1 y1)
let steep ((> abs) y1-y0 x1-x0)
Line 3,947 ⟶ 4,332:
when (error < 0)
y += ystep
error += deltax</langsyntaxhighlight>
=={{header|Wren}}==
{{libheader|DOME}}
Requires version 1.3.0 of DOME or later.
<syntaxhighlight lang="wren">import "graphics" for Canvas, ImageData, Color
import "dome" for Window
 
class Game {
static bmpCreate(name, w, h) { ImageData.create(name, w, h) }
 
static bmpFill(name, col) {
var image = ImageData[name]
for (x in 0...image.width) {
for (y in 0...image.height) image.pset(x, y, col)
}
}
 
static bmpPset(name, x, y, col) { ImageData[name].pset(x, y, col) }
 
static bmpPget(name, x, y) { ImageData[name].pget(x, y) }
 
static bmpLine(name, x0, y0, x1, y1, col) {
var dx = (x1 - x0).abs
var dy = (y1 - y0).abs
var sx = (x0 < x1) ? 1 : -1
var sy = (y0 < y1) ? 1 : -1
var err = ((dx > dy ? dx : - dy) / 2).floor
while (true) {
bmpPset(name, x0, y0, col)
if (x0 == x1 && y0 == y1) break
var e2 = err
if (e2 > -dx) {
err = err - dy
x0 = x0 + sx
}
if (e2 < dy) {
err = err + dx
y0 = y0 + sy
}
}
}
 
static init() {
Window.title = "Bresenham's line algorithm"
var size = 200
Window.resize(size, size)
Canvas.resize(size, size)
var name = "bresenham"
var bmp = bmpCreate(name, size, size)
bmpFill(name, Color.white)
bmpLine(name, 50, 100, 100, 190, Color.black)
bmpLine(name, 100, 190, 150, 100, Color.black)
bmpLine(name, 150, 100, 100, 10, Color.black)
bmpLine(name, 100, 10, 50, 100, Color.black)
bmp.draw(0, 0)
}
 
static update() {}
 
static draw(alpha) {}
}</syntaxhighlight>
 
=={{header|XPL0}}==
Bresenham line draw is built-in.
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
[SetVid($112); \set 640x480 graphics in 24-bit color
Move(10, 20); \set start of line segment
Line 3,957 ⟶ 4,402:
if ChIn(1) then []; \wait for keystroke while viewing graphic screen
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|zkl}}==
[[File:Line.zkl.jpg|200px|thumb]]
Algorithm from Wikipedia plus other functions so I can reference this code in other examples.
<langsyntaxhighlight lang="zkl">ppm:=PPM(200,200,0xFF|FF|FF);
ppm.line(50,100, 100,190, 0);
ppm.line(100,190, 150,100, 0);
Line 3,968 ⟶ 4,412:
ppm.line(100,10, 50,100, 0);
 
ppm.writeJPGFile("line.jpg");</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">class PPM{ // (0,0) is logically bottom left
fcn init(width,height,rgb=0){
sz:=width*height;
Line 4,058 ⟶ 4,502:
}
}
}</langsyntaxhighlight>
 
{{omit from|AWK}}
{{omit from|PARI/GP}}
 
[[Category:Geometry]]
Anonymous user