给定 image.RGBA
、坐标和一行文本,我如何添加带有任何普通固定字体的简单标签?例如。 Face7x13
来自 font/basicfont
.
package main
import (
"image"
"image/color"
"image/png"
"os"
)
func main() {
img := image.NewRGBA(image.Rect(0, 0, 320, 240))
x, y := 100, 100
addLabel(img, x, y, "Test123")
png.Encode(os.Stdout, img)
}
func addLabel(img *image.RGBA, x, y int, label string) {
col := color.Black
// now what?
}
对齐并不重要,但最好是我可以将标签写在从坐标开始的线上方。
而且我想避免像字体这样的外部可加载依赖项。
最佳答案
golang.org/x/image/font
包只定义了字体和在图像上绘制文本的接口(interface)。
您可以使用 Freetype 字体光栅器的 Go 实现:github.com/golang/freetype
.
key 类型是freetype.Context
,它有你需要的所有方法。
如需完整示例,请查看此文件:example/freetype/main.go
.此示例加载字体文件,创建和配置 freetype.Context
,在图像上绘制文本并将结果图像保存到文件中。
假设您已经加载了字体文件,并配置了 c
上下文(参见示例如何执行此操作)。那么您的 addLabel()
函数可能如下所示:
func addLabel(img *image.RGBA, x, y int, label string) {
c.SetDst(img)
size := 12.0 // font size in pixels
pt := freetype.Pt(x, y+int(c.PointToFixed(size)>>6))
if _, err := c.DrawString(label, pt); err != nil {
// handle error
}
}
如果您不想为 freetype
包和外部字体文件而烦恼,font/basicfont
包包含一个名为 Face7x13
的基本字体,其图形数据是完全独立的。你可以这样使用它:
import (
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
"image"
"image/color"
)
func addLabel(img *image.RGBA, x, y int, label string) {
col := color.RGBA{200, 100, 0, 255}
point := fixed.Point26_6{fixed.I(x), fixed.I(y)}
d := &font.Drawer{
Dst: img,
Src: image.NewUniform(col),
Face: basicfont.Face7x13,
Dot: point,
}
d.DrawString(label)
}
这就是 addLabel()
函数的使用方法:下面的代码创建一个新图像,在其上绘制 "Hello Go"
文本并将其保存在一个名为 hello-go.png
的文件:
func main() {
img := image.NewRGBA(image.Rect(0, 0, 300, 100))
addLabel(img, 20, 30, "Hello Go")
f, err := os.Create("hello-go.png")
if err != nil {
panic(err)
}
defer f.Close()
if err := png.Encode(f, img); err != nil {
panic(err)
}
}
请注意,上面的代码还需要 "image/png"
包导入。
还要注意,给定的 y
坐标将是文本的底线。所以如果你想在左上角画一条线,你必须使用x = 0
和y = 13
(13是这个Face7x13的高度
字体)。如果您愿意,您可以通过从 y
坐标中减去 13
将其构建到 addLabel()
函数中,这样传递的 y
坐标将是绘制文本的顶部坐标。
golang.org/x/image/font/inconsolata
中还有一个额外的自包含字体。具有常规和粗体样式的包,要使用它们,您只需指定不同的Face
在 addLabel()
:
import "golang.org/x/image/font/inconsolata"
// To use regular Inconsolata font family:
Face: inconsolata.Regular8x16,
// To use bold Inconsolata font family:
Face: inconsolata.Bold8x16,
关于image - 如何在 Go 中为图像添加简单的文本标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38299930/