twitchapon-anim

Basic Twitchapon Receiver/Visuals
git clone git://bsandro.tech/twitchapon-anim
Log | Files | Refs | README | LICENSE

gif_object.go (1842B)


      1 package main
      2 
      3 import (
      4 	"github.com/hajimehoshi/ebiten/v2"
      5 	"image"
      6 	"image/gif"
      7 	"os"
      8 	"time"
      9 )
     10 
     11 type TGifObject struct {
     12 	Anim       *gif.GIF
     13 	FrameNum   int
     14 	FrameTime  time.Time
     15 	FrameImage *ebiten.Image
     16 }
     17 
     18 func (obj *TGifObject) Update() error {
     19 	delay := int64(obj.Anim.Delay[obj.FrameNum])
     20 	cur_time := time.Now()
     21 	elapsed := cur_time.Sub(obj.FrameTime)
     22 
     23 	if obj.FrameImage != nil && elapsed.Milliseconds() < delay*10 {
     24 		return nil
     25 	}
     26 
     27 	// frame rectangle
     28 	var bounds image.Rectangle = obj.Anim.Image[obj.FrameNum].Bounds()
     29 	// base picture size
     30 	img_w, img_h := obj.Anim.Config.Width, obj.Anim.Config.Height
     31 	// frame image
     32 	src_img := ebiten.NewImageFromImage(obj.Anim.Image[obj.FrameNum])
     33 	//src_w, src_h := src_img.Size()
     34 	img_opts := &ebiten.DrawImageOptions{}
     35 	// shifting by rectangle properties
     36 	img_opts.GeoM.Translate(float64(bounds.Min.X), float64(bounds.Min.Y))
     37 
     38 	// image from reference size
     39 	obj.FrameImage = ebiten.NewImage(img_w, img_h)
     40 	//img.Fill(color.RGBA{0xF0, 0x10, 0x0F, 0xFF})
     41 
     42 	obj.FrameImage.DrawImage(src_img, img_opts)
     43 	obj.FrameTime = cur_time
     44 	obj.FrameNum += 1
     45 	if obj.FrameNum >= len(obj.Anim.Image) {
     46 		obj.FrameNum = 0
     47 	}
     48 
     49 	return nil
     50 }
     51 
     52 func (obj *TGifObject) Draw(screen *ebiten.Image) {
     53 	if obj.FrameImage != nil {
     54 		img_w, img_h := obj.Anim.Config.Width, obj.Anim.Config.Height
     55 		scr_w, scr_h := ScreenSize.width, ScreenSize.height
     56 		opts := &ebiten.DrawImageOptions{}
     57 		// center image
     58 		opts.GeoM.Translate(-float64(img_w/2), -float64(img_h/2))
     59 		opts.GeoM.Translate(float64(scr_w/2), float64(scr_h/2))
     60 
     61 		screen.DrawImage(obj.FrameImage, opts)
     62 	}
     63 }
     64 
     65 func MakeGifObject(file_path string) (obj *TGifObject, err error) {
     66 	obj = new(TGifObject)
     67 
     68 	fileReader, err := os.Open(file_path)
     69 	if err != nil {
     70 		return
     71 	}
     72 	obj.Anim, err = gif.DecodeAll(fileReader)
     73 	if err != nil {
     74 		return
     75 	}
     76 
     77 	return
     78 }