• Stars
    star
    4,245
  • Rank 9,668 (Top 0.2 %)
  • Language
    Go
  • License
    MIT License
  • Created about 8 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Go Graphics - 2D rendering in Go with a simple API.

Go Graphics

gg is a library for rendering 2D graphics in pure Go.

Stars

Installation

go get -u github.com/fogleman/gg

Alternatively, you may use gopkg.in to grab a specific major-version:

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

Documentation

Hello, Circle!

Look how easy!

package main

import "github.com/fogleman/gg"

func main() {
    dc := gg.NewContext(1000, 1000)
    dc.DrawCircle(500, 500, 400)
    dc.SetRGB(0, 0, 0)
    dc.Fill()
    dc.SavePNG("out.png")
}

Examples

There are lots of examples included. They're mostly for testing the code, but they're good for learning, too.

Examples

Creating Contexts

There are a few ways of creating a context.

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

Drawing Functions

Ever used a graphics library that didn't have functions for drawing rectangles or circles? What a pain!

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()

It is often desired to center an image at a point. Use DrawImageAnchored with ax and ay set to 0.5 to do this. Use 0 to left or top align. Use 1 to right or bottom align. DrawStringAnchored does the same for text, so you don't need to call MeasureString yourself.

Text Functions

It will even do word wrap for you!

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

Color Functions

Colors can be set in several different ways for your convenience.

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)

Stroke & Fill Options

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

Gradients & Patterns

gg supports linear, radial and conic gradients and surface patterns. You can also implement your own patterns.

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)

Transformation Functions

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()

It is often desired to rotate or scale about a point that is not the origin. The functions RotateAbout, ScaleAbout, ShearAbout are provided as a convenience.

InvertY is provided in case Y should increase from bottom to top vs. the default top to bottom.

Stack Functions

Save and restore the state of the context. These can be nested.

Push()
Pop()

Clipping Functions

Use clipping regions to restrict drawing operations to an area that you defined using paths.

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

Helper Functions

Sometimes you just don't want to write these yourself.

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

Another Example

See the output of this example below.

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

More Repositories

1

primitive

Reproducing images with geometric primitives.
Go
12,316
star
2

Craft

A simple Minecraft clone written in C using modern OpenGL (shaders).
C
10,151
star
3

nes

NES emulator written in Go.
Go
5,352
star
4

Minecraft

Simple Minecraft-inspired program using Python and Pyglet
Python
5,134
star
5

ln

3D line art engine.
Go
3,228
star
6

pt

A path tracer written in Go.
Go
2,065
star
7

sdf

Simple SDF mesh generation in Python
Python
1,465
star
8

Quads

Computer art based on quadtrees.
Python
1,160
star
9

physarum

Physarum polycephalum slime mold simulation
Go
845
star
10

fauxgl

Software-only 3D renderer written in Go.
Go
842
star
11

hmm

Heightmap meshing utility.
C
551
star
12

Tiling

Tilings of regular polygons.
Python
478
star
13

rbgg

Isolate and remove the background gradient from images of paper.
Go
343
star
14

pack3d

Tightly pack 3D models.
Go
319
star
15

rush

Rush Hour puzzle goodies!
Go
281
star
16

axi

Library for working with the AxiDraw v3 pen plotter.
Python
266
star
17

PirateMap

Procedurally generate pirate treasure maps.
Python
259
star
18

simplify

3D mesh simplification in Go.
Go
242
star
19

ribbon

Ribbon diagrams of proteins in #golang.
Go
240
star
20

Punchcard

Generate GitHub-style punchcard charts with ease.
Python
240
star
21

terrarium

Some code for generating topographic contour maps.
Go
219
star
22

pg

Python OpenGL Graphics Framework
Python
207
star
23

dlaf

Diffusion-limited aggregation, fast.
C++
179
star
24

FeedNotifier

Feed Notifier is a Windows application that resides in the system tray and displays pop-up notifications on your desktop when new items arrive in your subscribed RSS or Atom feeds
Python
163
star
25

CellularForms

An implementation of Andy Lomas' Cellular Forms.
C++
152
star
26

density

Render millions of points on a map.
Go
147
star
27

MisterQueen

A chess engine written in C.
C
141
star
28

meshview

Performant 3D mesh viewer written in Go.
Go
132
star
29

delaunay

Fast Delaunay triangulation implemented in Go.
Go
113
star
30

GraphLayout

Graph drawing using simulated annealing for layout.
Python
110
star
31

Piet

Procedurally Generating Images in the Style of Piet Mondrian
Python
97
star
32

ease

Easing functions in #golang.
Go
85
star
33

AdventOfCode2018

My solutions to the Advent of Code 2018 problems.
Python
81
star
34

iMeme

iMeme is a popular meme generator for Mac OS X
Objective-C
71
star
35

DCPU-16

Python scripts for DCPU-16 emulation.
DCPU-16 ASM
70
star
36

xy

Various utilities for the Makeblock XY Plotter Robot Kit
Python
69
star
37

contourmap

Compute contour lines (isolines) for any 2D data in Go.
Go
67
star
38

demsphere

Generate 3D meshes of planets, moons, etc. from spherical DEMs. (WIP)
Go
66
star
39

GPS

Real-time GPS Satellite Positions in 3D
Python
64
star
40

slicer

Fast 3D mesh slicer written in Go.
Go
61
star
41

AllRGB

Scripts for creating AllRGB images.
Python
60
star
42

mol

Render ball-and-stick models of molecules.
Go
58
star
43

pixsort

Applying the traveling salesman problem to pixel art.
Go
57
star
44

Ricochet

Implementation of Ricochet Robot (Rasende Roboter) including a GUI and a solver
Python
53
star
45

domaincoloring

Domain coloring in Go.
Go
50
star
46

Scale

Beautiful Fractals for Mac OS X.
Objective-C
40
star
47

gorgb

Program to create "allRGB" images.
Go
38
star
48

HelloFlask

A boiler-plate starting point for a Flask web application, including SQLAlchemy, WTForms and Bootstrap.
CSS
37
star
49

Field

Creating computer art by simulating charged particle field lines.
Python
36
star
50

serve

Simple Go file server for command line development use, a la Python's SimpleHTTPServer.
Go
34
star
51

choppy

Chop 3D models in half with a user-defined slice plane.
Go
34
star
52

TWL06

Official Scrabble dictionary packaged into a convenient Python module.
Python
32
star
53

Sync

Code inspired by the book.
Python
31
star
54

tracer

Global illumination path tracer in C++
C++
29
star
55

maps

Work in progress. Render maps in #golang with a simple API.
Go
27
star
56

FutureBlocks

Tetris clone written in QBasic.
Visual Basic
26
star
57

AdventOfCode2019

My solutions for Advent of Code 2019.
Python
25
star
58

HiRISE

Convert HiRISE PDS IMG files to 3D meshes with normal maps.
Python
25
star
59

AdventOfCode2021

My solutions for Advent of Code 2021.
Python
24
star
60

lissaknot

Create 3D models of Lissajous knots.
Go
24
star
61

LoginServer

Online multiplayer game login server for secure user authentication.
Python
23
star
62

pyMeme

Cross-platform meme generator application.
Python
23
star
63

ShortUrl

Python module for generating tiny URLs.
Python
22
star
64

imview

Simple image viewer written in Go + OpenGL.
Go
21
star
65

HelloGL

Basic project structure for an OpenGL application.
C
21
star
66

AdventOfCode2020

My solutions for Advent of Code 2020
Python
20
star
67

PieSlice

Making simple wallpapers out of quarter circles.
Python
20
star
68

GameFrame

Game Frame Simulator
Objective-C
19
star
69

Manhattan

Rendering the buildings of Manhattan using OSM data and NYC shapefiles.
Python
19
star
70

Phrases

Source code for a simple website that generates random, two-word phrases.
HTML
18
star
71

poissondisc

Poisson Disc sampling in Go.
Go
16
star
72

SwtPacMan

Pac-Man clone written in 2005 using Java + SWT.
Java
16
star
73

Mapper

Web app for quickly plotting markers, polylines, polygons, heatmaps, etc. on a map.
JavaScript
15
star
74

Mazes

Maze generation and rendering using Python.
Python
15
star
75

Poker

Python poker hand evaluator
Python
12
star
76

GrayScott

Simple Gray Scott Reaction Diffusion model implemented in C++ and OpenCL
C++
12
star
77

WangTiling

Weighted Wang tiling.
Python
12
star
78

mc

Marching cubes algorithm implemented in #golang.
Go
11
star
79

thumbs

Go binary that watches a folder for images and generates thumbnails of them.
Go
11
star
80

Fireflies

Synchronizing fireflies using JavaScript and D3.
10
star
81

go-airspy

Go wrapper for the libairspy library.
Go
10
star
82

go-embree

Simple golang wrapper for embree using cgo
C++
9
star
83

DrMario

Dr Mario clone in Python and wxPython, including AI
Python
9
star
84

WellPlate

Python + wxPython user interface for 96 and 384 well plates.
Python
9
star
85

triangulate

Polygon triangulation via ear clipping in #golang.
Go
8
star
86

platformer

It's happening!
Go
8
star
87

AdventOfCode2022

My solutions for Advent of Code 2022.
Python
8
star
88

AdventOfCode2023

My solutions to the Advent of Code 2023 puzzles.
Python
7
star
89

Yellow

Visualization for 2015 NYC Yellow Taxi Trips
JavaScript
7
star
90

motion

Constant acceleration motion planner written in Go.
Go
7
star
91

wxSnow

Falling snowflakes on your Windows desktop.
Python
7
star
92

Turing

2-D Turing Machine
Python
7
star
93

colormap

Colormaps for Go.
Go
6
star
94

go-maps

Utilities for rendering maps in Go.
Go
6
star
95

slices2stl

Go
6
star
96

Fractal

Fractals in Python!
Python
6
star
97

TextEditor

Scintilla-based text editor written in Python and wxPython
Python
6
star
98

Boggle

Web-based Boggle clone written using Python and Flask
Python
5
star
99

michaelfogleman.com

Source code for my personal website.
HTML
5
star
100

CurveMesh

Python
5
star