github.com/kintar/etxt@v0.0.9/examples/gtxt/hello_world/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  // Must be compiled with '-tags gtxt'
    16  
    17  func main() {
    18  	const OutImgWidth = 256
    19  	const OutImgHeight = 64
    20  	const TextSizePx = 32
    21  
    22  	// get font path
    23  	if len(os.Args) != 2 {
    24  		msg := "Usage: expects one argument with the path to the font to be used\n"
    25  		fmt.Fprint(os.Stderr, msg)
    26  		os.Exit(1)
    27  	}
    28  
    29  	// parse font
    30  	font, fontName, err := etxt.ParseFontFrom(os.Args[1])
    31  	if err != nil {
    32  		log.Fatal(err)
    33  	}
    34  	fmt.Printf("Font loaded: %s\n", fontName)
    35  
    36  	// create cache
    37  	cache := etxt.NewDefaultCache(1024 * 1024 * 1024) // 1GB cache
    38  
    39  	// create and configure renderer
    40  	renderer := etxt.NewStdRenderer()
    41  	renderer.SetCacheHandler(cache.NewHandler())
    42  	renderer.SetSizePx(TextSizePx)
    43  	renderer.SetFont(font)
    44  	renderer.SetAlign(etxt.YCenter, etxt.XCenter)
    45  	renderer.SetColor(color.RGBA{0, 0, 0, 255}) // black
    46  
    47  	// create target image and fill it with white
    48  	outImage := image.NewRGBA(image.Rect(0, 0, OutImgWidth, OutImgHeight))
    49  	for i := 0; i < OutImgWidth*OutImgHeight*4; i++ {
    50  		outImage.Pix[i] = 255
    51  	}
    52  
    53  	// set target and draw
    54  	renderer.SetTarget(outImage)
    55  	renderer.Draw("Hello World!", OutImgWidth/2, OutImgHeight/2)
    56  
    57  	// store image as png
    58  	filename, err := filepath.Abs("gtxt_hello_world.png")
    59  	if err != nil {
    60  		log.Fatal(err)
    61  	}
    62  	fmt.Printf("Output image: %s\n", filename)
    63  	file, err := os.Create(filename)
    64  	if err != nil {
    65  		log.Fatal(err)
    66  	}
    67  	err = png.Encode(file, outImage)
    68  	if err != nil {
    69  		log.Fatal(err)
    70  	}
    71  	err = file.Close()
    72  	if err != nil {
    73  		log.Fatal(err)
    74  	}
    75  	fmt.Print("Program exited successfully.\n")
    76  }