github.com/Kintar/etxt@v0.0.0-20221224033739-2fc69f000137/examples/ebiten/colorful/main.go (about) 1 package main 2 3 import "os" 4 import "log" 5 import "fmt" 6 import "math" 7 import "image/color" 8 9 import "github.com/hajimehoshi/ebiten/v2" 10 import "golang.org/x/image/math/fixed" 11 12 import "github.com/Kintar/etxt" 13 14 type Game struct { 15 txtRenderer *etxt.Renderer 16 redSrc float64 17 greenSrc float64 18 blueSrc float64 19 } 20 21 func (self *Game) Layout(w int, h int) (int, int) { return w, h } 22 func (self *Game) Update() error { 23 // progressively change the values to use in Draw to derive colors, 24 // at different speeds each one 25 self.redSrc -= 0.0202 26 self.greenSrc -= 0.0168 27 self.blueSrc -= 0.0227 28 return nil 29 } 30 31 func (self *Game) Draw(screen *ebiten.Image) { 32 // dark background 33 screen.Fill(color.RGBA{0, 0, 0, 255}) 34 offset := 0.0 35 36 // draw text 37 const MainText = "Colorful!\nWonderful!" 38 w, h := screen.Size() 39 self.txtRenderer.SetTarget(screen) 40 self.txtRenderer.Traverse(MainText, fixed.P(w/2, h/2), 41 func(dot fixed.Point26_6, codePoint rune, glyphIndex etxt.GlyphIndex) { 42 if codePoint == '\n' { 43 return 44 } // skip line breaks 45 46 // derive the color for the current letter from the Src values on 47 // each color channel, the current offset, and the sine function 48 r := (math.Sin(self.redSrc+offset) + 1.0) / 2.0 49 g := (math.Sin(self.greenSrc+offset) + 1.0) / 2.0 50 b := (math.Sin(self.blueSrc+offset) + 1.0) / 2.0 51 self.txtRenderer.SetColor(color.RGBA{uint8(r * 255), uint8(g * 255), uint8(b * 255), 255}) 52 53 // draw the glyph mask 54 mask := self.txtRenderer.LoadGlyphMask(glyphIndex, dot) 55 self.txtRenderer.DefaultDrawFunc(dot, mask, glyphIndex) 56 57 // increase offset to apply to the next letters 58 offset += 0.15 59 }) 60 } 61 62 func main() { 63 // get font path 64 if len(os.Args) != 2 { 65 msg := "Usage: expects one argument with the path to the font to be used\n" 66 fmt.Fprint(os.Stderr, msg) 67 os.Exit(1) 68 } 69 70 // parse font 71 font, fontName, err := etxt.ParseFontFrom(os.Args[1]) 72 if err != nil { 73 log.Fatal(err) 74 } 75 fmt.Printf("Font loaded: %s\n", fontName) 76 77 // create cache 78 cache := etxt.NewDefaultCache(1024 * 1024 * 1024) // 1GB cache 79 80 // create and configure renderer 81 renderer := etxt.NewStdRenderer() 82 renderer.SetCacheHandler(cache.NewHandler()) 83 renderer.SetSizePx(64) 84 renderer.SetFont(font) 85 renderer.SetAlign(etxt.YCenter, etxt.XCenter) 86 87 // run the game 88 ebiten.SetWindowTitle("etxt/examples/ebiten/colorful") 89 ebiten.SetWindowSize(640, 480) 90 err = ebiten.RunGame(&Game{renderer, -5.54, -4.3, -6.4}) 91 if err != nil { 92 log.Fatal(err) 93 } 94 }