标准 Go 库不提供原始绘图或绘画功能。
它提供的是颜色模型(image/color http://golang.org/pkg/image/color/包)和一个Image http://golang.org/pkg/image/#Image具有多个实现的接口(image http://golang.org/pkg/image/包裹)。博客文章Go 镜像包 http://blog.golang.org/go-image-package对此有一个很好的介绍。
它还提供了将图像与不同操作结合起来的能力(例如,将它们相互绘制)image/draw http://golang.org/pkg/image/draw/包裹。它的用途远比乍听起来要多得多。有一篇关于image/draw
软件包展示了它的一些潜力:Go 图像/绘图包 http://blog.golang.org/go-imagedraw-package
另一个例子是开源游戏地鼠迷宫 https://github.com/gophergala/golab (披露:我是作者)它有一个图形界面,它只使用标准 Go 库来组装其视图。
它是开源的,请查看其来源,了解它是如何完成的。它有一个可滚动的游戏视图,其中包含移动图像/动画。
标准库还支持读写常见图像格式,例如GIF http://golang.org/pkg/image/gif/, JPEG http://golang.org/pkg/image/jpeg/, PNG http://golang.org/pkg/image/png/,并且对其他格式的支持是开箱即用的:BMP http://godoc.org/golang.org/x/image/bmp, RIFF http://godoc.org/golang.org/x/image/riff, TIFF http://godoc.org/golang.org/x/image/tiff乃至WEBP http://godoc.org/golang.org/x/image/webp(仅一个读取器/解码器)。
尽管标准库没有提供支持,但在图像上绘制线条和矩形相当容易。给定一个img
支持使用以下方法更改像素的图像:Set(x, y int, c color.Color)
(例如image.RGBA http://golang.org/pkg/image/#RGBA对我们来说是完美的)和col
类型的color.Color http://golang.org/pkg/image/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
file:
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)
}
如果你想绘制文字,你可以使用FreeType 的 Go 实现 https://github.com/golang/freetype。另请查看此问题,了解在图像上绘制字符串的简单介绍:如何在 Go 中向图像添加简单的文本标签? https://stackoverflow.com/questions/38299930/how-do-add-a-text-label-to-an-image-in-go
如果您想要高级和更复杂的绘图功能,还有许多外部库 https://github.com/golang/go/wiki/Projects#graphics-and-audio可用,例如:
https://github.com/llgcode/draw2d https://github.com/llgcode/draw2d
https://github.com/fogleman/gg https://github.com/fogleman/gg