github.com/kintar/etxt@v0.0.9/examples/gtxt/rainbow/main.go (about) 1 //go:build gtxt 2 3 package main 4 5 import "os" 6 import "image" 7 import "image/color" 8 import "image/png" 9 import "path/filepath" 10 import "log" 11 import "fmt" 12 13 import "github.com/kintar/etxt" 14 15 import "golang.org/x/image/math/fixed" 16 17 // Must be compiled with '-tags gtxt' 18 19 // NOTE: see gtxt/mirror if you want a more advanced example of drawing each 20 // character individually. This one uses the renderer's DefaultDrawFunc, 21 // so all the heavy lifting is already done. 22 23 func main() { 24 // get font path 25 if len(os.Args) != 2 { 26 msg := "Usage: expects one argument with the path to the font to be used\n" 27 fmt.Fprint(os.Stderr, msg) 28 os.Exit(1) 29 } 30 31 // parse font 32 font, fontName, err := etxt.ParseFontFrom(os.Args[1]) 33 if err != nil { 34 log.Fatal(err) 35 } 36 fmt.Printf("Font loaded: %s\n", fontName) 37 38 // create and configure renderer 39 // (we omit the cache as we don't reuse any letters anyway...) 40 renderer := etxt.NewStdRenderer() 41 renderer.SetSizePx(48) 42 renderer.SetFont(font) 43 renderer.SetAlign(etxt.YCenter, etxt.XCenter) 44 45 // create target image and fill it with a white to black gradient 46 outImage := image.NewRGBA(image.Rect(0, 0, 256, 64)) 47 for y := 0; y < 64; y++ { 48 lvl := 255 - uint8(y*8) 49 if y >= 32 { 50 lvl = 255 - lvl 51 } 52 for x := 0; x < 256; x++ { 53 outImage.Set(x, y, color.RGBA{lvl, lvl, lvl, 255}) 54 } 55 } 56 57 // set target and prepare rainbow colors 58 renderer.SetTarget(outImage) 59 colors := []color.RGBA{ 60 color.RGBA{R: 255, G: 0, B: 0, A: 255}, // red 61 color.RGBA{R: 255, G: 165, B: 0, A: 255}, // orange 62 color.RGBA{R: 255, G: 255, B: 0, A: 255}, // yellow 63 color.RGBA{R: 0, G: 255, B: 0, A: 255}, // green 64 color.RGBA{R: 0, G: 0, B: 255, A: 255}, // blue 65 color.RGBA{R: 75, G: 0, B: 130, A: 255}, // indigo 66 color.RGBA{R: 238, G: 130, B: 238, A: 255}, // violet 67 } 68 69 // draw each letter with a different color 70 colorIndex := 0 71 renderer.Traverse("RAINBOW", fixed.P(128, 32), 72 func(dot fixed.Point26_6, _ rune, glyphIndex etxt.GlyphIndex) { 73 renderer.SetColor(colors[colorIndex]) 74 mask := renderer.LoadGlyphMask(glyphIndex, dot) 75 renderer.DefaultDrawFunc(dot, mask, glyphIndex) 76 colorIndex += 1 77 }) 78 79 // store result as png 80 filename, err := filepath.Abs("gtxt_rainbow.png") 81 if err != nil { 82 log.Fatal(err) 83 } 84 fmt.Printf("Output image: %s\n", filename) 85 file, err := os.Create(filename) 86 if err != nil { 87 log.Fatal(err) 88 } 89 err = png.Encode(file, outImage) 90 if err != nil { 91 log.Fatal(err) 92 } 93 err = file.Close() 94 if err != nil { 95 log.Fatal(err) 96 } 97 fmt.Print("Program exited successfully.\n") 98 }