golang纯Go实现的2D图形渲染插件库gg的使用

Go Graphics (gg) - 纯Go实现的2D图形渲染库

gg 是一个用纯Go语言实现的2D图形渲染库。

Stars

安装

go get -u github.com/fogleman/gg

或者使用gopkg.in获取特定主版本:

go get -u gopkg.in/fogleman/gg.v1

文档

Hello, Circle!

看有多简单!

package main

import "github.com/fogleman/gg"

func main() {
    dc := gg.NewContext(1000, 1000)  // 创建1000x1000的画布
    dc.DrawCircle(500, 500, 400)     // 在(500,500)位置画半径为400的圆
    dc.SetRGB(0, 0, 0)               // 设置颜色为黑色
    dc.Fill()                        // 填充
    dc.SavePNG("out.png")            // 保存为PNG
}

示例

包含了许多示例,主要用于测试代码,但也适合学习。

Examples

创建上下文

有几种创建上下文的方法:

NewContext(width, height int) *Context
NewContextForImage(im image.Image) *Context
NewContextForRGBA(im *image.RGBA) *Context

绘图函数

DrawPoint(x, y, r float64)
DrawLine(x1, y1, x2, y2 float64)
DrawRectangle(x, y, w, h float64)
DrawRoundedRectangle(x, y, w, h, r float64)
DrawCircle(x, y, r float64)
DrawArc(x, y, r, angle1, angle2 float64)
DrawEllipse(x, y, rx, ry float64)
DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64)
DrawRegularPolygon(n int, x, y, r, rotation float64)
DrawImage(im image.Image, x, y int)
DrawImageAnchored(im image.Image, x, y int, ax, ay float64)
SetPixel(x, y int)

MoveTo(x, y float64)
LineTo(x, y float64)
QuadraticTo(x1, y1, x2, y2 float64)
CubicTo(x1, y1, x2, y2, x3, y3 float64)
ClosePath()
ClearPath()
NewSubPath()

Clear()
Stroke()
Fill()
StrokePreserve()
FillPreserve()

文本函数

DrawString(s string, x, y float64)
DrawStringAnchored(s string, x, y, ax, ay float64)
DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing float64, align Align)
MeasureString(s string) (w, h float64)
MeasureMultilineString(s string, lineSpacing float64) (w, h float64)
WordWrap(s string, w float64) []string
SetFontFace(fontFace font.Face)
LoadFontFace(path string, points float64) error

颜色函数

SetRGB(r, g, b float64)
SetRGBA(r, g, b, a float64)
SetRGB255(r, g, b int)
SetRGBA255(r, g, b, a int)
SetColor(c color.Color)
SetHexColor(x string)

描边和填充选项

SetLineWidth(lineWidth float64)
SetLineCap(lineCap LineCap)
SetLineJoin(lineJoin LineJoin)
SetDash(dashes ...float64)
SetDashOffset(offset float64)
SetFillRule(fillRule FillRule)

渐变和图案

SetFillStyle(pattern Pattern)
SetStrokeStyle(pattern Pattern)
NewSolidPattern(color color.Color)
NewLinearGradient(x0, y0, x1, y1 float64)
NewRadialGradient(x0, y0, r0, x1, y1, r1 float64)
NewConicGradient(cx, cy, deg float64)
NewSurfacePattern(im image.Image, op RepeatOp)

变换函数

Identity()
Translate(x, y float64)
Scale(x, y float64)
Rotate(angle float64)
Shear(x, y float64)
ScaleAbout(sx, sy, x, y float64)
RotateAbout(angle, x, y float64)
ShearAbout(sx, sy, x, y float64)
TransformPoint(x, y float64) (tx, ty float64)
InvertY()

堆栈函数

Push()
Pop()

裁剪函数

Clip()
ClipPreserve()
ResetClip()
AsMask() *image.Alpha
SetMask(mask *image.Alpha)
InvertMask()

辅助函数

Radians(degrees float64) float64
Degrees(radians float64) float64
LoadImage(path string) (image.Image, error)
LoadPNG(path string) (image.Image, error)
SavePNG(path string, im image.Image) error

Separator

另一个示例

package main

import "github.com/fogleman/gg"

func main() {
    const S = 1024
    dc := gg.NewContext(S, S)
    dc.SetRGBA(0, 0, 0, 0.1)  // 设置半透明黑色
    for i := 0; i < 360; i += 15 {
        dc.Push()  // 保存当前状态
        // 绕中心点旋转
        dc.RotateAbout(gg.Radians(float64(i)), S/2, S/2)
        // 绘制椭圆
        dc.DrawEllipse(S/2, S/2, S*7/16, S/8)
        dc.Fill()  // 填充
        dc.Pop()   // 恢复之前的状态
    }
    dc.SavePNG("out.png")
}

Ellipses


更多关于golang纯Go实现的2D图形渲染插件库gg的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang纯Go实现的2D图形渲染插件库gg的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Go语言2D图形渲染库gg使用指南

gg是一个纯Go实现的2D图形渲染库,它提供了简单易用的API来创建各种2D图形和图像处理操作。以下是gg库的主要功能和使用方法。

安装

首先安装gg库:

go get -u github.com/fogleman/gg

基本用法

创建画布

package main

import (
	"github.com/fogleman/gg"
)

func main() {
	// 创建一个800x600的白色背景画布
	dc := gg.NewContext(800, 600)
	dc.SetRGB(1, 1, 1) // 白色
	dc.Clear()
	
	// 绘制一个红色矩形
	dc.SetRGB(1, 0, 0) // 红色
	dc.DrawRectangle(100, 100, 200, 100)
	dc.Fill()
	
	// 保存为PNG文件
	dc.SavePNG("output.png")
}

绘制基本形状

// 绘制圆形
dc.DrawCircle(400, 300, 50) // 圆心(400,300),半径50
dc.SetRGB(0, 0, 1) // 蓝色
dc.Fill()

// 绘制线条
dc.SetRGB(0, 0, 0) // 黑色
dc.SetLineWidth(5) // 线宽5像素
dc.DrawLine(50, 50, 200, 200)
dc.Stroke()

// 绘制多边形
points := []gg.Point{
	{X: 500, Y: 100},
	{X: 600, Y: 150},
	{X: 550, Y: 250},
	{X: 450, Y: 250},
	{X: 400, Y: 150},
}
dc.DrawPolygon(points)
dc.SetRGB(0, 1, 0) // 绿色
dc.FillPreserve()  // 填充并保留路径
dc.SetRGB(0, 0, 0) // 黑色
dc.Stroke()        // 描边

文本渲染

// 加载字体
if err := dc.LoadFontFace("arial.ttf", 36); err != nil {
	panic(err)
}

// 绘制文本
dc.SetRGB(0, 0, 0) // 黑色
dc.DrawString("Hello, gg!", 300, 400)

// 带轮廓的文本
dc.SetRGB(1, 1, 1) // 白色填充
dc.DrawStringAnchored("Go语言", 400, 300, 0.5, 0.5)
dc.SetRGB(0, 0, 0) // 黑色轮廓
dc.SetLineWidth(2)
dc.Stroke()

图像操作

// 加载图像
img, err := gg.LoadImage("input.jpg")
if err != nil {
	panic(err)
}

// 绘制图像
dc.DrawImage(img, 0, 0)

// 缩放图像
dc.DrawImageAnchored(img, 400, 300, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5)

// 旋转图像
dc.Push()
dc.RotateAbout(gg.Radians(45), 400, 300) // 旋转45度
dc.DrawImageAnchored(img, 400, 300, 0.5, 0.5)
dc.Pop()

变换和裁剪

// 平移
dc.Push()
dc.Translate(100, 100)
dc.DrawRectangle(0, 0, 100, 100)
dc.Fill()
dc.Pop()

// 缩放
dc.Push()
dc.Scale(0.5, 0.5)
dc.DrawRectangle(400, 300, 100, 100)
dc.Fill()
dc.Pop()

// 裁剪
dc.DrawCircle(400, 300, 100)
dc.Clip()
dc.DrawRectangle(300, 200, 200, 200)
dc.Fill()
dc.ResetClip()

渐变填充

// 线性渐变
grad := gg.NewLinearGradient(100, 100, 300, 300)
grad.AddColorStop(0, color.RGBA{255, 0, 0, 255})   // 红色
grad.AddColorStop(0.5, color.RGBA{0, 255, 0, 255}) // 绿色
grad.AddColorStop(1, color.RGBA{0, 0, 255, 255})   // 蓝色

dc.SetFillStyle(grad)
dc.DrawRectangle(100, 100, 200, 200)
dc.Fill()

// 径向渐变
grad = gg.NewRadialGradient(500, 300, 0, 500, 300, 100)
grad.AddColorStop(0, color.RGBA{255, 255, 0, 255}) // 黄色
grad.AddColorStop(1, color.RGBA{255, 0, 255, 255}) // 紫色

dc.SetFillStyle(grad)
dc.DrawCircle(500, 300, 100)
dc.Fill()

高级示例:绘制饼图

func drawPieChart(dc *gg.Context, x, y, r float64, data []float64, colors []color.Color) {
	var sum float64
	for _, v := range data {
		sum += v
	}
	
	var a1, a2 float64
	for i, v := range data {
		// 计算角度
		a2 = a1 + v/sum*2*math.Pi
		
		// 绘制扇形
		dc.MoveTo(x, y)
		dc.SetColor(colors[i%len(colors)])
		dc.DrawArc(x, y, r, a1, a2)
		dc.LineTo(x, y)
		dc.Fill()
		
		a1 = a2
	}
}

func main() {
	dc := gg.NewContext(800, 600)
	dc.SetRGB(1, 1, 1)
	dc.Clear()
	
	data := []float64{30, 20, 15, 10, 25}
	colors := []color.Color{
		color.RGBA{255, 0, 0, 255},
		color.RGBA{0, 255, 0, 255},
		color.RGBA{0, 0, 255, 255},
		color.RGBA{255, 255, 0, 255},
		color.RGBA{255, 0, 255, 255},
	}
	
	drawPieChart(dc, 400, 300, 200, data, colors)
	dc.SavePNG("pie_chart.png")
}

总结

gg库提供了丰富的2D图形绘制功能,包括:

  • 基本形状绘制(矩形、圆形、线条、多边形等)
  • 文本渲染(支持TrueType字体)
  • 图像操作(加载、绘制、变换)
  • 图形变换(平移、旋转、缩放)
  • 渐变填充(线性和径向)
  • 裁剪和蒙版

gg库API设计简洁,适合快速开发2D图形应用,如数据可视化、简单游戏、图像处理等。由于是纯Go实现,它可以在任何支持Go的平台运行,无需外部依赖。

回到顶部