| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package drawing |
| 5 |
|
| 6 |
|
| 7 |
func NewLineStroker(c LineCap, j LineJoin, flattener Flattener) *LineStroker { |
| 8 |
l := new(LineStroker) |
| 9 |
l.Flattener = flattener |
| 10 |
l.HalfLineWidth = 0.5 |
| 11 |
l.Cap = c |
| 12 |
l.Join = j |
| 13 |
return l |
| 14 |
} |
| 15 |
|
| 16 |
|
| 17 |
type LineStroker struct { |
| 18 |
Flattener Flattener |
| 19 |
HalfLineWidth float64 |
| 20 |
Cap LineCap |
| 21 |
Join LineJoin |
| 22 |
vertices []float64 |
| 23 |
rewind []float64 |
| 24 |
x, y, nx, ny float64 |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
func (l *LineStroker) MoveTo(x, y float64) { |
| 29 |
l.x, l.y = x, y |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
func (l *LineStroker) LineTo(x, y float64) { |
| 34 |
l.line(l.x, l.y, x, y) |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
func (l *LineStroker) LineJoin() {} |
| 39 |
|
| 40 |
func (l *LineStroker) line(x1, y1, x2, y2 float64) { |
| 41 |
dx := (x2 - x1) |
| 42 |
dy := (y2 - y1) |
| 43 |
d := vectorDistance(dx, dy) |
| 44 |
if d != 0 { |
| 45 |
nx := dy * l.HalfLineWidth / d |
| 46 |
ny := -(dx * l.HalfLineWidth / d) |
| 47 |
l.appendVertex(x1+nx, y1+ny, x2+nx, y2+ny, x1-nx, y1-ny, x2-nx, y2-ny) |
| 48 |
l.x, l.y, l.nx, l.ny = x2, y2, nx, ny |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
func (l *LineStroker) Close() { |
| 54 |
if len(l.vertices) > 1 { |
| 55 |
l.appendVertex(l.vertices[0], l.vertices[1], l.rewind[0], l.rewind[1]) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
func (l *LineStroker) End() { |
| 61 |
if len(l.vertices) > 1 { |
| 62 |
l.Flattener.MoveTo(l.vertices[0], l.vertices[1]) |
| 63 |
for i, j := 2, 3; j < len(l.vertices); i, j = i+2, j+2 { |
| 64 |
l.Flattener.LineTo(l.vertices[i], l.vertices[j]) |
| 65 |
} |
| 66 |
} |
| 67 |
for i, j := len(l.rewind)-2, len(l.rewind)-1; j > 0; i, j = i-2, j-2 { |
| 68 |
l.Flattener.LineTo(l.rewind[i], l.rewind[j]) |
| 69 |
} |
| 70 |
if len(l.vertices) > 1 { |
| 71 |
l.Flattener.LineTo(l.vertices[0], l.vertices[1]) |
| 72 |
} |
| 73 |
l.Flattener.End() |
| 74 |
|
| 75 |
l.vertices = l.vertices[0:0] |
| 76 |
l.rewind = l.rewind[0:0] |
| 77 |
l.x, l.y, l.nx, l.ny = 0, 0, 0, 0 |
| 78 |
|
| 79 |
} |
| 80 |
|
| 81 |
func (l *LineStroker) appendVertex(vertices ...float64) { |
| 82 |
s := len(vertices) / 2 |
| 83 |
l.vertices = append(l.vertices, vertices[:s]...) |
| 84 |
l.rewind = append(l.rewind, vertices[s:]...) |
| 85 |
} |