Last active
January 26, 2020 05:51
-
-
Save quillaja/23b38d736669dae18dc6ad2427eb1bc8 to your computer and use it in GitHub Desktop.
Go version of Bresenham's line algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// plotline draws a simple line on img from (x0,y0) to (x1,y1). | |
// | |
// This is basically a copy of a version of Bresenham's line algorithm | |
// from https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm. | |
func plotline(img draw.Image, c color.Color, x0, y0, x1, y1 int) { | |
dx := abs(x1 - x0) | |
sx := -1 | |
if x0 < x1 { | |
sx = 1 | |
} | |
dy := -abs(y1 - y0) | |
sy := -1 | |
if y0 < y1 { | |
sy = 1 | |
} | |
err := dx + dy | |
for { | |
img.Set(x0, y0, c) | |
if x0 == x1 && y0 == y1 { | |
break | |
} | |
e2 := 2 * err | |
if e2 >= dy { | |
err += dy | |
x0 += sx | |
} | |
if e2 <= dx { | |
err += dx | |
y0 += sy | |
} | |
} | |
} | |
// abs cuz no integer abs function in the Go standard library. | |
func abs(x int) int { | |
if x < 0 { | |
return -x | |
} | |
return x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment