英文:
Code has to load a font file, how to embed inside the built binary
问题
我有一个Go包中的代码。它必须加载cmr10.ttf
字体文件。因此,字体文件必须与使用该包的每个可执行文件放在一起。
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))
}
问题
有没有办法避免将cmr10.ttf
字体文件复制到使用该包的任何可执行文件旁边?
例如,是否可以将字体文件嵌入到构建的二进制文件中?如果可能的话,具体如何操作?
还有其他尝试的想法吗?
英文:
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?
答案1
得分: 1
从Go 1.16开始,go工具支持直接将静态文件嵌入可执行二进制文件中。您可以使用//go:embed
指令嵌入字体文件的二进制数据:
import (
_ "embed"
)
//go:embed cmr10.ttf
var cmr10FontData []byte
编译器将把cmr10.ttf
的内容插入到cmr10FontData
变量中。有关其他选项,请参阅https://stackoverflow.com/questions/13904441/whats-the-best-way-to-bundle-static-resources-in-a-go-program/28071360#28071360
现在,由于github.com/deadsy/sdfx/sdf
只提供了一个sdf.LoadFont(fname)
辅助函数,您必须使用github.com/golang/freetype/truetype
来解析字体数据。请注意,sdf.LoadFont()
也在内部使用它,使用字体文件的二进制数据调用truetype.Parse()
:
f, err := truetype.Parse(cmr10FontData)
// 检查错误
// 如果没有错误,使用f
英文:
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 https://stackoverflow.com/questions/13904441/whats-the-best-way-to-bundle-static-resources-in-a-go-program/28071360#28071360
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论