github.com/kintar/etxt@v0.0.9/examples/gtxt/sizer_expand/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  import "github.com/kintar/etxt/esizer"
    15  
    16  // Must be compiled with '-tags gtxt'
    17  
    18  func main() {
    19  	// get font path
    20  	if len(os.Args) != 2 {
    21  		msg := "Usage: expects one argument with the path to the font to be used\n"
    22  		fmt.Fprint(os.Stderr, msg)
    23  		os.Exit(1)
    24  	}
    25  
    26  	// parse font
    27  	font, fontName, err := etxt.ParseFontFrom(os.Args[1])
    28  	if err != nil {
    29  		log.Fatal(err)
    30  	}
    31  	fmt.Printf("Font loaded: %s\n", fontName)
    32  
    33  	// create cache
    34  	cache := etxt.NewDefaultCache(1024 * 1024 * 1024) // 1GB cache
    35  
    36  	// create and configure renderer
    37  	renderer := etxt.NewStdRenderer()
    38  	renderer.SetCacheHandler(cache.NewHandler())
    39  	renderer.SetSizePx(32)
    40  	renderer.SetFont(font)
    41  	renderer.SetAlign(etxt.YCenter, etxt.XCenter)
    42  	renderer.SetColor(color.RGBA{255, 255, 255, 255}) // white
    43  
    44  	// create sizer and set it too
    45  	padSizer := &esizer.HorzPaddingSizer{}
    46  	renderer.SetSizer(padSizer)
    47  
    48  	// create target image and fill it with black
    49  	outImage := image.NewRGBA(image.Rect(0, 0, 600, 230))
    50  	for i := 3; i < 600*230*4; i += 4 {
    51  		outImage.Pix[i] = 255
    52  	}
    53  
    54  	// set target and draw each line expanding more and more
    55  	renderer.SetTarget(outImage)
    56  	for i := 0; i < 6; i++ {
    57  		padSizer.SetHorzPadding(i * 12) // *
    58  		renderer.Draw("pyramid", 300, (i+1)*32)
    59  
    60  		// * alternative code if we didn't have the sizer locally:
    61  		// sizer := renderer.GetSizer().(*esizer.HorzPaddingSizer)
    62  		// sizer.SetHorzPadding(i*12)
    63  	}
    64  
    65  	// store image as png
    66  	filename, err := filepath.Abs("gtxt_sizer_expand.png")
    67  	if err != nil {
    68  		log.Fatal(err)
    69  	}
    70  	fmt.Printf("Output image: %s\n", filename)
    71  	file, err := os.Create(filename)
    72  	if err != nil {
    73  		log.Fatal(err)
    74  	}
    75  	err = png.Encode(file, outImage)
    76  	if err != nil {
    77  		log.Fatal(err)
    78  	}
    79  	err = file.Close()
    80  	if err != nil {
    81  		log.Fatal(err)
    82  	}
    83  	fmt.Print("Program exited successfully.\n")
    84  }