Debian Codegraph @

vendor/github.com/xyproto/gfx/bresenham.go

raw
1 package gfx
2
3 import (
4 "image/color"
5 "image/draw"
6 "math"
7 )
8
9 // DrawLineBresenham draws a line using Bresenham's line algorithm.
10 //
11 // http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
12 func DrawLineBresenham(dst draw.Image, from, to Vec, c color.Color) {
13 x0, y0 := from.XY()
14 x1, y1 := to.XY()
15
16 steep := math.Abs(y0-y1) > math.Abs(x0-x1)
17
18 if steep {
19 x0, y0 = y0, x0
20 x1, y1 = y1, x1
21 }
22
23 if x0 > x1 {
24 x0, x1 = x1, x0
25 y0, y1 = y1, y0
26 }
27
28 dx := x1 - x0
29 dy := math.Abs(y1 - y0)
30 e := dx / 2
31 y := y0
32
33 var ystep float64 = -1
34
35 if y0 < y1 {
36 ystep = 1
37 }
38
39 for x := x0; x <= x1; x++ {
40 if steep {
41 Mix(dst, int(y), int(x), c)
42 } else {
43 Mix(dst, int(x), int(y), c)
44 }
45
46 e -= dy
47
48 if e < 0 {
49 y += ystep
50 e += dx
51 }
52 }
53 }