Skip to content

Instantly share code, notes, and snippets.

@stjohnjohnson
Last active March 3, 2020 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stjohnjohnson/f39530c6ec12d44523a492f8a64da2b2 to your computer and use it in GitHub Desktop.
Save stjohnjohnson/f39530c6ec12d44523a492f8a64da2b2 to your computer and use it in GitHub Desktop.
// Animate triggers the application to redraw every 50ms
func Animate(app *tview.Application) {
globalAnimationMutex.Lock()
defer globalAnimationMutex.Unlock()
for {
app.QueueUpdateDraw(func() {})
time.Sleep(50 * time.Millisecond)
}
}
// GetCurrentFrame returns the current frame the GIF is on
func (g *GifView) GetCurrentFrame() int {
// If no duration, we're on frame 0
if g.totalDuration == 0 {
return 0
}
// Mod allows us to continuously loop
dur := time.Since(g.startTime) % g.totalDuration
for i, d := range g.delay {
dur -= d
if dur < 0 {
return i
}
}
return 0
}
func (g *GifView) Draw(screen tcell.Screen) {
g.Lock()
defer g.Unlock()
currentFrame := g.GetCurrentFrame()
frame := strings.Split(g.frames[currentFrame], "\n")
x, y, w, _ := g.GetInnerRect()
for i, line := range frame {
tview.Print(screen, line, x, y+i, w, tview.AlignLeft, tcell.ColorWhite)
}
}
package main
import (
"fmt"
"github.com/rivo/tview"
"github.com/stjohnjohnson/gifview"
)
func main() {
// Create the application
a := tview.NewApplication()
// Create our dancing banana gif
img, err := gifview.FromImagePath("banana.gif")
if err != nil {
panic(fmt.Errorf("Unable to load gif: %v", err))
}
// Set the banana as our root layer
a.SetRoot(img, true)
// Trigger animation
go gifview.Animate(a)
// Start the application
if err := a.Run(); err != nil {
panic(err)
}
}
file, err := os.Open("correct.gif")
if err != nil {
return fmt.Errorf("Unable to open file: %v", err)
}
defer file.Close()
image, err := gif.DecodeAll(file)
if err != nil {
return fmt.Errorf("Unable to decode GIF: %v", err)
}
textView := tview.NewTextView()
textView.SetDynamicColors(true)
for i, img := range image.Image {
txt, err := pixelview.FromImage(img)
if err != nil {
return fmt.Errorf("Unable to parse frame: %v", err)
}
// Draw the image
textView.SetText(txt)
// Sleep the delay of the frame
time.Sleep(image.Delay[i] * time.Millisecond)
}
file, err := os.Open("correct.gif")
if err != nil {
return fmt.Errorf("Unable to open file: %v", err)
}
defer file.Close()
image, err := gif.DecodeAll(file)
if err != nil {
return fmt.Errorf("Unable to decode GIF: %v", err)
}
for i, img := range image.Image {
// Attempt to print the image
fmt.Printf("Frame %d: %v", i, img)
// Sleep the delay of the frame
time.Sleep(image.Delay[i] * time.Millisecond)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment