1

I have this code inside a Go package of mine. It must load the cmr10.ttf font file. So, the font file must be next to every executable which is using this package.


import (
    "github.com/deadsy/sdfx/sdf"
)

func Text(txt string, height, thickness, roundness float32) (sdf.SDF3, error) {
    f, err := sdf.LoadFont("cmr10.ttf")
    if err != nil {
        return nil, err
    }

    t := sdf.NewText(txt)

    s2d, err := sdf.TextSDF2(f, t, float64(height))
    if err != nil {
        return nil, err
    }

    // Extrude the 2D SDF to a 3D SDF.
    return sdf.ExtrudeRounded3D(s2d, float64(thickness), float64(roundness))
}

Question

Is there a way to avoid copying the cmr10.ttf font file next to any executable using this package?

For example, like embedding the font file into the built binary. If possible, how to exactly do it?

Any other idea to try?

Megidd
  • 7,089
  • 6
  • 65
  • 142

1 Answers1

1

Starting with Go 1.16 the go tool has support for embedding static files directly in the executable binary. You can embed the binary data of the font file using the //go:embed directive:

import (
    _ "embed"
)

//go:embed cmr10.ttf
var cmr10FontData []byte

The content of cmr10.ttf will be inserted into the cmr10FontData variable by the compiler. For other options see What's the best way to bundle static resources in a Go program?

Now since github.com/deadsy/sdfx/sdf only offers an sdf.LoadFont(fname) helper function, you have to use github.com/golang/freetype/truetype to parse the font data. Note that sdf.LoadFont() also uses this under the hood, calling truetype.Parse() with the binary data of the font file:

f, err := truetype.Parse(cmr10FontData)
// Check error
// use f if no error
icza
  • 389,944
  • 63
  • 907
  • 827