标准 Go 库不提供原始绘图或绘画功能。
它提供的是颜色模型(image/color 包)和带有多个实现的Image 接口(@987654323@ 包)。博文The Go Image package 对此进行了很好的介绍。
它还提供了在 image/draw 包中使用不同操作组合图像(例如,将它们相互绘制)的功能。这可以比一开始听起来要多得多。有一篇关于 image/draw 软件包的精彩博客文章展示了它的一些潜力:The Go image/draw package
另一个例子是开源游戏Gopher's Labyrinth(披露:我是作者),它有一个图形界面,它只使用标准 Go 库来组装它的视图。
它是开源的,请查看它的源代码是如何完成的。它有一个可滚动的游戏视图,其中包含移动图像/动画。
标准库还支持读写常见的图像格式,如GIF、JPEG、PNG,并且开箱即可支持其他格式:BMP、RIFF、TIFF甚至WEBP(只有一个阅读器/解码器)。
虽然标准库不提供支持,但在图像上绘制线条和矩形相当容易。给定一个支持使用方法更改像素的img 图像:Set(x, y int, c color.Color)(例如image.RGBA 非常适合我们)和col 类型的color.Color:
// HLine draws a horizontal line
func HLine(x1, y, x2 int) {
for ; x1 <= x2; x1++ {
img.Set(x1, y, col)
}
}
// VLine draws a veritcal line
func VLine(x, y1, y2 int) {
for ; y1 <= y2; y1++ {
img.Set(x, y1, col)
}
}
// Rect draws a rectangle utilizing HLine() and VLine()
func Rect(x1, y1, x2, y2 int) {
HLine(x1, y1, x2)
HLine(x1, y2, x2)
VLine(x1, y1, y2)
VLine(x2, y1, y2)
}
这里使用这些简单的函数是一个可运行的示例程序,它绘制一条线和一个矩形并将图像保存到.png 文件中:
import (
"image"
"image/color"
"image/png"
"os"
)
var img = image.NewRGBA(image.Rect(0, 0, 100, 100))
var col color.Color
func main() {
col = color.RGBA{255, 0, 0, 255} // Red
HLine(10, 20, 80)
col = color.RGBA{0, 255, 0, 255} // Green
Rect(10, 10, 80, 50)
f, err := os.Create("draw.png")
if err != nil {
panic(err)
}
defer f.Close()
png.Encode(f, img)
}
如果要绘制文字,可以使用Go implementation of FreeType。还可以查看这个问题,了解在图像上绘制字符串的简单介绍:How to add a simple text label to an image in Go?
如果你想要更高级更复杂的绘图功能,也有many external libraries可用,例如:
https://github.com/llgcode/draw2d
https://github.com/fogleman/gg