| 1 |
//go:build !tinygo |
| 2 |
// +build !tinygo |
| 3 |
|
| 4 |
package gfx |
| 5 |
|
| 6 |
import ( |
| 7 |
"image" |
| 8 |
"image/color" |
| 9 |
"image/draw" |
| 10 |
"image/gif" |
| 11 |
"io" |
| 12 |
) |
| 13 |
|
| 14 |
// DefaultAnimationDelay is the default animation delay, in 100ths of a second. |
| 15 |
var DefaultAnimationDelay = 50 |
| 16 |
|
| 17 |
// Animation represents multiple images. |
| 18 |
type Animation struct { |
| 19 |
Frames []image.Image // The successive images. |
| 20 |
Palettes []color.Palette // The successive palettes. |
| 21 |
|
| 22 |
Delay int // Delay between each of the frames. |
| 23 |
|
| 24 |
// LoopCount controls the number of times an animation will be |
| 25 |
// restarted during display. |
| 26 |
// A LoopCount of 0 means to loop forever. |
| 27 |
// A LoopCount of -1 means to show each frame only once. |
| 28 |
// Otherwise, the animation is looped LoopCount+1 times. |
| 29 |
LoopCount int |
| 30 |
} |
| 31 |
|
| 32 |
// AddPalettedImage adds a frame and palette to the animation. |
| 33 |
func (a *Animation) AddPalettedImage(frame PalettedImage) { |
| 34 |
a.Frames = append(a.Frames, frame) |
| 35 |
a.Palettes = append(a.Palettes, frame.ColorPalette()) |
| 36 |
} |
| 37 |
|
| 38 |
// AddFrame adds a frame to the animation. |
| 39 |
func (a *Animation) AddFrame(frame image.Image, palette color.Palette) { |
| 40 |
a.Frames = append(a.Frames, frame) |
| 41 |
a.Palettes = append(a.Palettes, palette) |
| 42 |
} |
| 43 |
|
| 44 |
// SaveGIF saves the animation to a GIF using the provided file name. |
| 45 |
func (a *Animation) SaveGIF(fn string) error { |
| 46 |
w, err := CreateFile(fn) |
| 47 |
if err != nil { |
| 48 |
return err |
| 49 |
} |
| 50 |
defer w.Close() |
| 51 |
|
| 52 |
return a.EncodeGIF(w) |
| 53 |
} |
| 54 |
|
| 55 |
// EncodeGIF writes the animation to w in GIF format with the |
| 56 |
// given loop count and delay between frames. |
| 57 |
func (a *Animation) EncodeGIF(w io.Writer) error { |
| 58 |
if len(a.Frames) != len(a.Palettes) { |
| 59 |
return Error("Animation: the number of Frames and Palettes does not match") |
| 60 |
} |
| 61 |
|
| 62 |
if a.Delay < 1 { |
| 63 |
a.Delay = DefaultAnimationDelay |
| 64 |
} |
| 65 |
|
| 66 |
var frames []*image.Paletted |
| 67 |
var delays []int |
| 68 |
var disposal []byte |
| 69 |
|
| 70 |
for i, src := range a.Frames { |
| 71 |
dst := image.NewPaletted(src.Bounds(), a.Palettes[i]) |
| 72 |
|
| 73 |
draw.Draw(dst, dst.Bounds(), src, image.Point{}, draw.Src) |
| 74 |
|
| 75 |
frames = append(frames, dst) |
| 76 |
delays = append(delays, a.Delay) |
| 77 |
disposal = append(disposal, gif.DisposalBackground) |
| 78 |
} |
| 79 |
|
| 80 |
return gif.EncodeAll(w, &gif.GIF{ |
| 81 |
Image: frames, |
| 82 |
Delay: delays, |
| 83 |
LoopCount: a.LoopCount, |
| 84 |
Disposal: disposal, |
| 85 |
}) |
| 86 |
} |