| 1 |
package drawing |
| 2 |
|
| 3 |
import ( |
| 4 |
"image/color" |
| 5 |
"image/draw" |
| 6 |
) |
| 7 |
|
| 8 |
|
| 9 |
func PolylineBresenham(img draw.Image, c color.Color, s ...float64) { |
| 10 |
for i := 2; i < len(s); i += 2 { |
| 11 |
Bresenham(img, c, int(s[i-2]+0.5), int(s[i-1]+0.5), int(s[i]+0.5), int(s[i+1]+0.5)) |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
|
| 16 |
func Bresenham(img draw.Image, color color.Color, x0, y0, x1, y1 int) { |
| 17 |
dx := abs(x1 - x0) |
| 18 |
dy := abs(y1 - y0) |
| 19 |
var sx, sy int |
| 20 |
if x0 < x1 { |
| 21 |
sx = 1 |
| 22 |
} else { |
| 23 |
sx = -1 |
| 24 |
} |
| 25 |
if y0 < y1 { |
| 26 |
sy = 1 |
| 27 |
} else { |
| 28 |
sy = -1 |
| 29 |
} |
| 30 |
err := dx - dy |
| 31 |
|
| 32 |
var e2 int |
| 33 |
for { |
| 34 |
img.Set(x0, y0, color) |
| 35 |
if x0 == x1 && y0 == y1 { |
| 36 |
return |
| 37 |
} |
| 38 |
e2 = 2 * err |
| 39 |
if e2 > -dy { |
| 40 |
err = err - dy |
| 41 |
x0 = x0 + sx |
| 42 |
} |
| 43 |
if e2 < dx { |
| 44 |
err = err + dx |
| 45 |
y0 = y0 + sy |
| 46 |
} |
| 47 |
} |
| 48 |
} |