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