From ea4556c36b52462a47318ab9e616c8dda6a09fdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ximo=20Cuadros?= Date: Sun, 12 Mar 2017 00:30:38 +0100 Subject: [PATCH] ToolKit: added PlayImageUntil and now Animation uses PlayImageUntil --- examples/animation/main.go | 9 +++++---- toolkit.go | 22 ++++++++++++++++++---- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/examples/animation/main.go b/examples/animation/main.go index c50511c..e329fbc 100644 --- a/examples/animation/main.go +++ b/examples/animation/main.go @@ -3,6 +3,7 @@ package main import ( "flag" "image" + "image/color" "time" "github.com/fogleman/gg" @@ -57,16 +58,16 @@ func NewAnimation(sz image.Point) *Animation { } } -func (a *Animation) Next() (image.Image, time.Duration, error) { +func (a *Animation) Next() (image.Image, <-chan time.Time, error) { defer a.updatePosition() - a.ctx.SetRGB(0, 0, 0) + a.ctx.SetColor(color.Black) a.ctx.Clear() a.ctx.DrawCircle(float64(a.position.X), float64(a.position.Y), float64(a.stroke)) - a.ctx.SetRGB(1, 0, 0) + a.ctx.SetColor(color.RGBA{255, 0, 0, 0}) a.ctx.Fill() - return a.ctx.Image(), time.Millisecond * 50, nil + return a.ctx.Image(), time.After(time.Millisecond * 50), nil } func (a *Animation) updatePosition() { diff --git a/toolkit.go b/toolkit.go index d8639b8..f5500d7 100644 --- a/toolkit.go +++ b/toolkit.go @@ -44,7 +44,7 @@ func (tk *ToolKit) PlayImage(i image.Image, delay time.Duration) error { } type Animation interface { - Next() (image.Image, time.Duration, error) + Next() (image.Image, <-chan time.Time, error) } // PlayAnimation play the image during the delay returned by Next, until an err @@ -52,15 +52,15 @@ type Animation interface { func (tk *ToolKit) PlayAnimation(a Animation) error { var err error var i image.Image - var d time.Duration + var n <-chan time.Time for { - i, d, err = a.Next() + i, n, err = a.Next() if err != nil { break } - if err := tk.PlayImage(i, d); err != nil { + if err := tk.PlayImageUntil(i, n); err != nil { return err } } @@ -72,6 +72,20 @@ func (tk *ToolKit) PlayAnimation(a Animation) error { return err } +// PlayImageUntil draws the given image until is notified to stop +func (tk *ToolKit) PlayImageUntil(i image.Image, notify <-chan time.Time) error { + defer func() { + <-notify + }() + + if tk.Transform != nil { + i = tk.Transform(i) + } + + draw.Draw(tk.Canvas, tk.Canvas.Bounds(), i, image.ZP, draw.Over) + return tk.Canvas.Render() +} + // PlayImages draws a sequence of images during the given delays, the len of // images should be equal to the len of delay. If loop is true the function // loops over images until a true is sent to the returned chan