代码:
package main
import (
"image"
"image/gif"
"image/color"
"os"
"math"
"io"
)
var palette = []color.Color{color.Black,color.RGBA{0,255,0,255}}
const (
blackIndex = 0
greenIndex = 1
)
func main() {
drawSin(os.Stdout)
}
func drawSin(out io.Writer) {
const (
nframes = 80 //帧数
resolution = 0.0001 //分辨率
size = 300 //画布大小
delay = 10 //延迟
)
anim := gif.GIF{LoopCount: nframes}
x := 0.0
for i := 0; i < nframes; i++ {
rect := image.Rect(0,0,size,size)
img := image.NewPaletted(rect,palette)
for t := 0.0; t < size; t += resolution {
y := size / 2 *math.Sin(t + x);
img.SetColorIndex(int(t + 0.5),int(size / 2 + y),greenIndex)
}
x += 3 * resolution
anim.Delay = append(anim.Delay,delay)
anim.Image = append(anim.Image,img)
}
gif.EncodeAll(out,&anim)
}
效果: