-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path09_gif_animation.go
85 lines (74 loc) · 2.12 KB
/
09_gif_animation.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
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Patnáctá část
// Programovací jazyk Go a grafika: tvorba animovaných GIFů, grafická knihovna GG
// https://www.root.cz/clanky/programovaci-jazyk-go-a-grafika-tvorba-animovanych-gifu-graficka-knihovna-gg/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z patnácté části:
// https://github.com/tisnik/go-root/blob/master/article_15/README.md
//
// Demonstrační příklad číslo 9:
// Složitější animace pohybující se šachovnice
//
// Dokumentace ve stylu "literate programming":
// https://tisnik.github.io/go-root/article_15/09_gif_animation.html
package main
import (
"image"
"image/color"
"image/draw"
"image/gif"
"os"
)
// BoardSize represents size of chessboard being rendered
const BoardSize = 8
func CreateChessboard(width int, height int, boardSize int, xoffset int, yoffset int, stepSize int) *image.Paletted {
var palette = []color.Color{
color.RGBA{150, 205, 50, 255},
color.RGBA{0, 100, 0, 255},
}
img := image.NewPaletted(image.Rect(0, 0, width, height), palette)
indexColor := 0
horBlock := int(width / boardSize)
verBlock := int(height / boardSize)
xFrom := 0
xTo := horBlock
for x := 0; x < boardSize+stepSize; x++ {
yFrom := 0
yTo := verBlock
for y := 0; y < boardSize+stepSize; y++ {
r := image.Rect(xFrom+xoffset, yFrom+yoffset, xTo+xoffset, yTo+yoffset)
draw.Draw(img, r, &image.Uniform{palette[indexColor]}, image.ZP, draw.Src)
yFrom = yTo
yTo += verBlock
indexColor = 1 - indexColor
}
xFrom = xTo
xTo += horBlock
indexColor = 1 - indexColor
}
return img
}
func main() {
var images []*image.Paletted
var delays []int
steps := 2 * 256 / BoardSize
for step := 0; step < steps; step++ {
img := CreateChessboard(256, 256, BoardSize, step*2-steps*2, step-steps, steps*2)
images = append(images, img)
delays = append(delays, 10)
}
outfile, err := os.Create("09.gif")
if err != nil {
panic(err)
}
defer outfile.Close()
gif.EncodeAll(outfile, &gif.GIF{
Image: images,
Delay: delays,
})
}