github.com/Kintar/etxt@v0.0.0-20221224033739-2fc69f000137/examples/gtxt/shape/main.go (about)

     1  //go:build gtxt
     2  
     3  package main
     4  
     5  import "os"
     6  import "log"
     7  import "fmt"
     8  import "image/color"
     9  import "image/png"
    10  import "path/filepath"
    11  
    12  import "github.com/Kintar/etxt/emask"
    13  
    14  // An example of how to use emask.Shape in isolation. This has nothing
    15  // to do with fonts, but it can still come in handy in games. There's
    16  // actually another, more practical and simpler example of emask.Shape
    17  // within examples/ebiten/shaking. There's also a crazier random shape
    18  // generator in examples/ebiten/rng_shape.
    19  
    20  func main() {
    21  	// create a new shape, preallocating a buffer with capacity
    22  	// for at least 128 segments so we won't have extra allocations
    23  	// later. not like it matters much for such a small example.
    24  	shape := emask.NewShape(128)
    25  
    26  	// draw a diamond shape repeatedly, each time smaller.
    27  	// inverting the y each time leads each diamond to be
    28  	// drawn in a different order (clockwise/counter-clockwise),
    29  	// which leads to the shape being patterned on and off
    30  	for i := 0; i < 20; i += 2 {
    31  		shape.InvertY(!shape.HasInvertY()) // comment to disable the pattern
    32  		x := 80 - i
    33  		shape.MoveTo(0, x)
    34  		shape.LineTo(x, 0)
    35  		shape.LineTo(0, -x)
    36  		shape.LineTo(-x, 0)
    37  		shape.LineTo(0, x)
    38  	}
    39  
    40  	// try uncommenting for a weird effect
    41  	//shape.InvertY(!shape.HasInvertY())
    42  
    43  	// draw a few concentric squares
    44  	for i := 0; i < 20; i += 4 {
    45  		shape.InvertY(!shape.HasInvertY())
    46  		x := 50 - i
    47  		shape.MoveTo(-x, x)
    48  		shape.LineTo(x, x)
    49  		shape.LineTo(x, -x)
    50  		shape.LineTo(-x, -x)
    51  		shape.LineTo(-x, x)
    52  	}
    53  
    54  	// use the handy Paint function to go from an alpha mask
    55  	// to a RGBA image. in general if you are feeling less
    56  	// fancy you simply use (color.White, color.Black)
    57  	emerald := color.RGBA{80, 200, 120, 255}
    58  	catawba := color.RGBA{119, 51, 68, 255}
    59  	outImage := shape.Paint(emerald, catawba)
    60  
    61  	// print the path where we will store the result
    62  	filename, err := filepath.Abs("gtxt_shape.png")
    63  	if err != nil {
    64  		log.Fatal(err)
    65  	}
    66  	fmt.Printf("Output image: %s\n", filename)
    67  
    68  	// actually store the result
    69  	file, err := os.Create(filename)
    70  	if err != nil {
    71  		panic(err)
    72  	}
    73  	err = png.Encode(file, outImage)
    74  	if err != nil {
    75  		panic(err)
    76  	}
    77  
    78  	// bye bye
    79  	fmt.Print("Program exited successfully.\n")
    80  }