Code archives/Graphics/Besenham's LineDraw routine
This code has been declared by its author to be Public Domain code.
Download source code
| Uses all integer math. Credit for originally writing this code goes to ImaginaryHuman's BlitzMax code. I needed it for Blitz+ so I changed it, and figured there was no reason not to put it here. |
;Bresenham linedraw Graphics 640,480,0,2 Repeat Cls bLine(320,240,MouseX(),MouseY()) Flip Until KeyHit(1) End Function bLine(X1,Y1,X2,Y2) ;Draws a Line of individual pixels from X1,Y1 To X2,Y2 at any angle Local Steep=Abs(Y2-Y1) > Abs(X2-X1) ;Boolean If Steep Local Temp=X1: X1=Y1: Y1=Temp ;Swap X1,Y1 Temp=X2: X2=Y2: Y2=Temp ;Swap X2,Y2 EndIf Local DeltaX=Abs(X2-X1) ;X Difference Local DeltaY=Abs(Y2-Y1) ;Y Difference Local Error=0 ;Overflow counter Local DeltaError=DeltaY ;Counter adder Local X=X1 ;Start at X1,Y1 Local Y=Y1 Local XStep Local YStep If X1<X2 Then XStep=1 Else XStep=-1 ;Direction If Y1<Y2 Then YStep=1 Else YStep=-1 ;Direction If Steep Then Plot Y,X Else Plot X,Y ;Draw While X<>X2 X=X+XStep ;Move in X Error=Error+DeltaError ;Add To counter If (Error Shl 1)>DeltaX ;Would it overflow? Y=Y+YStep ;Move in Y Error=Error-DeltaX ;Overflow/wrap the counter EndIf If Steep Then Plot Y,X Else Plot X,Y ;Draw Wend End Function |