-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcanvas.go
109 lines (89 loc) · 2.16 KB
/
canvas.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Reference: http://www.pheelicks.com/2013/11/intro-to-images-in-go-fractals/
package main
// Import packages
import ("image"; "image/color"; "image/draw";
"os"
"log")
// Declare a new structure
type Canvas struct {
image.RGBA
}
func NewCanvas(r image.Rectangle) *Canvas {
canvas := new(Canvas)
canvas.RGBA = *image.NewRGBA(r)
return canvas
}
func (c Canvas) Clone() *Canvas {
clone := NewCanvas(c.Bounds())
copy(clone.Pix, c.Pix)
return clone
}
func (c Canvas) DrawGradient() {
size := c.Bounds().Size()
for x := 0; x < size.X; x++ {
for y := 0; y < size.Y; y++ {
color := color.RGBA{
uint8(255 * x / size.X),
uint8(255 * y / size.Y),
55,
255}
c.Set(x, y, color)
}
}
}
func (c Canvas) DrawLine(color color.RGBA, from Coordinate, to Coordinate) {
delta := to.Sub(from)
length := delta.Length()
xStep, yStep := delta.X/length, delta.Y/length
limit := int(length+0.5)
for i:=0; i<limit; i++ {
x := from.X + float64(i)*xStep
y := from.Y + float64(i)*yStep
c.Set(int(x), int(y), color)
}
}
func (c Canvas) DrawSpiral(color color.RGBA, from Coordinate, iterations uint32,
degree float64, factor float64) {
dir := Coordinate{0, 3.5}
last := from
var i uint32
// Iterations defines the number of small lines drawn
for i = 0; i<iterations; i++ {
next := last.Add(dir)
c.DrawLine(color, last, next)
// Only rotation will create a circle
dir.Rotate(degree)
// This scaling is the one which is doing the magic
dir.Scale(factor)
last = next
}
}
func (c Canvas) DrawRect(color color.RGBA, from Coordinate, to Coordinate) {
for x := int(from.X); x<=int(to.X); x++ {
for y := int(from.Y); y <= int(to.Y); y++ {
c.Set(x, y, color)
}
}
}
func (c Canvas) SaveToFile(fileName string) {
file, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// png.Encode(file, c.RGBA)
}
func CreateCanvas(fileName string) *Canvas {
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
log.Fatal(err)
}
c := NewCanvas(img.Bounds())
draw.Draw(c, img.Bounds(), img, image.ZP, draw.Src)
return c
}