给定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
软件包仅定义了字体界面和图像上的绘图文本的接口。
您可以使用Freetype字体光栅化器的Go实现github.com/golang/freetype
。
密钥类型是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.Int26_6(x * 64), fixed.Int26_6(y * 64)}
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
(该Face7x13
字体的高度为13 )。如果愿意,可以addLabel()
通过13
从y
坐标中减去来将其构建到函数中,以便传递的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,
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句