Documentation
¶
Overview ¶
Package gg provides a simple 2D graphics library for Go.
Overview ¶
gg is a Pure Go 2D graphics library inspired by fogleman/gg and designed to integrate with the GoGPU ecosystem. It provides an immediate-mode drawing API similar to HTML Canvas, with both software and GPU rendering backends.
Quick Start ¶
import "github.com/gogpu/gg"
// Create a drawing context (dc = drawing context convention)
dc := gg.NewContext(512, 512)
// Draw shapes
dc.SetRGB(1, 0, 0)
dc.DrawCircle(256, 256, 100)
dc.Fill()
// Save to PNG
dc.SavePNG("output.png")
API Compatibility ¶
The API is designed to be compatible with fogleman/gg for easy migration. Most fogleman/gg code should work with minimal changes.
Renderers ¶
The library includes both software and GPU-accelerated renderers:
- Software rasterizer for broad compatibility
- GPU renderer via gogpu/wgpu for high performance
Architecture ¶
The library is organized into:
- Public API: Context, Path, Paint, Matrix, Point
- Internal: raster (scanline), path (tessellation), blend (compositing)
- Renderers: software, gpu (wgpu)
Coordinate System ¶
Uses standard computer graphics coordinates:
- Origin (0,0) at top-left
- X increases right
- Y increases down
- Angles in radians, 0 is right, increases counter-clockwise
Performance ¶
The software renderer prioritizes correctness. For performance-critical applications, use the GPU renderer.
Index ¶
- Constants
- Variables
- func SolveCubic(a, b, c, d float64) []float64
- func SolveCubicInUnitInterval(a, b, c, d float64) []float64
- func SolveQuadratic(a, b, c float64) []float64
- func SolveQuadraticInUnitInterval(a, b, c float64) []float64
- type BlendMode
- type Brush
- func BrushFromPattern(p Pattern) Brushdeprecated
- type Close
- type ColorFunc
- type ColorStop
- type Context
- func (c *Context) AsMask() *Mask
- func (c *Context) Clear()
- func (c *Context) ClearDash()
- func (c *Context) ClearMask()
- func (c *Context) ClearPath()
- func (c *Context) ClearWithColor(col RGBA)
- func (c *Context) Clip()
- func (c *Context) ClipPreserve()
- func (c *Context) ClipRect(x, y, w, h float64)
- func (c *Context) Close() error
- func (c *Context) ClosePath()
- func (c *Context) CreateImagePattern(img *ImageBuf, x, y, w, h int) Pattern
- func (c *Context) CubicTo(c1x, c1y, c2x, c2y, x, y float64)
- func (c *Context) DrawArc(x, y, r, angle1, angle2 float64)
- func (c *Context) DrawCircle(x, y, r float64)
- func (c *Context) DrawEllipse(x, y, rx, ry float64)
- func (c *Context) DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64)
- func (c *Context) DrawImage(img *ImageBuf, x, y float64)
- func (c *Context) DrawImageEx(img *ImageBuf, opts DrawImageOptions)
- func (c *Context) DrawLine(x1, y1, x2, y2 float64)
- func (c *Context) DrawPoint(x, y, r float64)
- func (c *Context) DrawRectangle(x, y, w, h float64)
- func (c *Context) DrawRegularPolygon(n int, x, y, r, rotation float64)
- func (c *Context) DrawRoundedRectangle(x, y, w, h, r float64)
- func (c *Context) DrawString(s string, x, y float64)
- func (c *Context) DrawStringAnchored(s string, x, y, ax, ay float64)
- func (c *Context) EncodeJPEG(w io.Writer, quality int) error
- func (c *Context) EncodePNG(w io.Writer) error
- func (c *Context) Fill()
- func (c *Context) FillBrush() Brush
- func (c *Context) FillPreserve()
- func (c *Context) Font() text.Face
- func (c *Context) GetCurrentPoint() (x, y float64, ok bool)
- func (c *Context) GetMask() *Mask
- func (c *Context) GetStroke() Stroke
- func (c *Context) Height() int
- func (c *Context) Identity()
- func (c *Context) Image() image.Image
- func (c *Context) InvertMask()
- func (c *Context) InvertY()
- func (c *Context) IsDashed() bool
- func (c *Context) LineTo(x, y float64)
- func (c *Context) LoadFontFace(path string, points float64) errordeprecated
- func (c *Context) MeasureString(s string) (w, h float64)
- func (c *Context) MoveTo(x, y float64)
- func (c *Context) NewSubPath()
- func (c *Context) Pop()
- func (c *Context) PopLayer()
- func (c *Context) Push()
- func (c *Context) PushLayer(blendMode BlendMode, opacity float64)
- func (c *Context) QuadraticTo(cx, cy, x, y float64)
- func (c *Context) ResetClip()
- func (c *Context) Rotate(angle float64)
- func (c *Context) RotateAbout(angle, x, y float64)
- func (c *Context) SavePNG(path string) error
- func (c *Context) Scale(x, y float64)
- func (c *Context) SetBlendMode(_ BlendMode)
- func (c *Context) SetColor(col color.Color)
- func (c *Context) SetDash(lengths ...float64)
- func (c *Context) SetDashOffset(offset float64)
- func (c *Context) SetFillBrush(b Brush)
- func (c *Context) SetFillPattern(pattern Pattern)
- func (c *Context) SetFillRule(rule FillRule)
- func (c *Context) SetFont(face text.Face)
- func (c *Context) SetHexColor(hex string)
- func (c *Context) SetLineCap(lineCap LineCap)
- func (c *Context) SetLineJoin(join LineJoin)
- func (c *Context) SetLineWidth(width float64)
- func (c *Context) SetMask(mask *Mask)
- func (c *Context) SetMiterLimit(limit float64)
- func (c *Context) SetPixel(x, y int, col RGBA)
- func (c *Context) SetRGB(r, g, b float64)
- func (c *Context) SetRGBA(r, g, b, a float64)
- func (c *Context) SetStroke(stroke Stroke)
- func (c *Context) SetStrokeBrush(b Brush)
- func (c *Context) SetStrokePattern(pattern Pattern)
- func (c *Context) Shear(x, y float64)
- func (c *Context) Stroke()
- func (c *Context) StrokeBrush() Brush
- func (c *Context) StrokePreserve()
- func (c *Context) TransformPoint(x, y float64) (float64, float64)
- func (c *Context) Translate(x, y float64)
- func (c *Context) Width() int
- type CubicBez
- func (c CubicBez) BoundingBox() Rect
- func (c CubicBez) Deriv() QuadBez
- func (c CubicBez) End() Point
- func (c CubicBez) Eval(t float64) Point
- func (c CubicBez) Extrema() []float64
- func (c CubicBez) Inflections() []float64
- func (c CubicBez) Normal(t float64) Vec2
- func (c CubicBez) Start() Point
- func (c CubicBez) Subdivide() (CubicBez, CubicBez)
- func (c CubicBez) Subsegment(t0, t1 float64) CubicBez
- func (c CubicBez) Tangent(t float64) Vec2
- type CubicTo
- type CustomBrush
- func Checkerboard(c0, c1 RGBA, size float64) CustomBrush
- func HorizontalGradient(c0, c1 RGBA, x0, x1 float64) CustomBrush
- func LinearGradient(c0, c1 RGBA, x0, y0, x1, y1 float64) CustomBrush
- func NewCustomBrush(fn ColorFunc) CustomBrush
- func RadialGradient(c0, c1 RGBA, cx, cy, r float64) CustomBrush
- func Stripes(c0, c1 RGBA, width, angle float64) CustomBrush
- func VerticalGradient(c0, c1 RGBA, y0, y1 float64) CustomBrush
- type Dash
- type DrawImageOptions
- type ExtendMode
- type FillRule
- type ImageBuf
- type ImageFormat
- type ImagePattern
- type InterpolationMode
- type Layer
- type Line
- type LineCap
- type LineJoin
- type LineTo
- type LinearGradientBrush
- type Mask
- func (m *Mask) At(x, y int) uint8
- func (m *Mask) Bounds() image.Rectangle
- func (m *Mask) Clear()
- func (m *Mask) Clone() *Mask
- func (m *Mask) Data() []uint8
- func (m *Mask) Fill(value uint8)
- func (m *Mask) Height() int
- func (m *Mask) Invert()
- func (m *Mask) Set(x, y int, value uint8)
- func (m *Mask) Width() int
- type Matrix
- type MoveTo
- type Paint
- func (p *Paint) Clone() *Paint
- func (p *Paint) ColorAt(x, y float64) RGBA
- func (p *Paint) EffectiveDash() *Dash
- func (p *Paint) EffectiveLineCap() LineCap
- func (p *Paint) EffectiveLineJoin() LineJoin
- func (p *Paint) EffectiveLineWidth() float64
- func (p *Paint) EffectiveMiterLimit() float64
- func (p *Paint) GetBrush() Brush
- func (p *Paint) GetStroke() Stroke
- func (p *Paint) IsDashed() bool
- func (p *Paint) SetBrush(b Brush)
- func (p *Paint) SetStroke(s Stroke)
- type Path
- func (p *Path) Arc(cx, cy, r, angle1, angle2 float64)
- func (p *Path) Area() float64
- func (p *Path) BoundingBox() Rect
- func (p *Path) Circle(cx, cy, r float64)
- func (p *Path) Clear()
- func (p *Path) Clone() *Path
- func (p *Path) Close()
- func (p *Path) Contains(pt Point) bool
- func (p *Path) CubicTo(c1x, c1y, c2x, c2y, x, y float64)
- func (p *Path) CurrentPoint() Point
- func (p *Path) Elements() []PathElement
- func (p *Path) Ellipse(cx, cy, rx, ry float64)
- func (p *Path) Flatten(tolerance float64) []Point
- func (p *Path) FlattenCallback(tolerance float64, fn func(pt Point))
- func (p *Path) HasCurrentPoint() bool
- func (p *Path) Length(accuracy float64) float64
- func (p *Path) LineTo(x, y float64)
- func (p *Path) MoveTo(x, y float64)
- func (p *Path) QuadraticTo(cx, cy, x, y float64)
- func (p *Path) Rectangle(x, y, w, h float64)
- func (p *Path) Reversed() *Path
- func (p *Path) RoundedRectangle(x, y, w, h, r float64)
- func (p *Path) Transform(m Matrix) *Path
- func (p *Path) Winding(pt Point) int
- type PathBuilder
- func (b *PathBuilder) Build() *Path
- func (b *PathBuilder) Circle(cx, cy, r float64) *PathBuilder
- func (b *PathBuilder) Close() *PathBuilder
- func (b *PathBuilder) CubicTo(c1x, c1y, c2x, c2y, x, y float64) *PathBuilder
- func (b *PathBuilder) Ellipse(cx, cy, rx, ry float64) *PathBuilder
- func (b *PathBuilder) LineTo(x, y float64) *PathBuilder
- func (b *PathBuilder) MoveTo(x, y float64) *PathBuilder
- func (b *PathBuilder) Path() *Path
- func (b *PathBuilder) Polygon(cx, cy, radius float64, sides int) *PathBuilder
- func (b *PathBuilder) QuadTo(cx, cy, x, y float64) *PathBuilder
- func (b *PathBuilder) Rect(x, y, w, h float64) *PathBuilder
- func (b *PathBuilder) RoundRect(x, y, w, h, r float64) *PathBuilder
- func (b *PathBuilder) Star(cx, cy, outerRadius, innerRadius float64, points int) *PathBuilder
- type PathElement
- type Pattern
- func PatternFromBrush(b Brush) Patterndeprecated
- type Pixmap
- func (p *Pixmap) At(x, y int) color.Color
- func (p *Pixmap) Bounds() image.Rectangle
- func (p *Pixmap) Clear(c RGBA)
- func (p *Pixmap) ColorModel() color.Model
- func (p *Pixmap) Data() []uint8
- func (p *Pixmap) EncodeJPEG(w io.Writer, quality int) error
- func (p *Pixmap) EncodePNG(w io.Writer) error
- func (p *Pixmap) FillSpan(x1, x2, y int, c RGBA)
- func (p *Pixmap) FillSpanBlend(x1, x2, y int, c RGBA)
- func (p *Pixmap) GetPixel(x, y int) RGBA
- func (p *Pixmap) Height() int
- func (p *Pixmap) SavePNG(path string) error
- func (p *Pixmap) Set(x, y int, c color.Color)
- func (p *Pixmap) SetPixel(x, y int, c RGBA)
- func (p *Pixmap) ToImage() *image.RGBA
- func (p *Pixmap) Width() int
- type Point
- func (p Point) Add(q Point) Point
- func (p Point) Cross(q Point) float64
- func (p Point) Distance(q Point) float64
- func (p Point) Div(s float64) Point
- func (p Point) Dot(q Point) float64
- func (p Point) Length() float64
- func (p Point) LengthSquared() float64
- func (p Point) Lerp(q Point, t float64) Point
- func (p Point) Mul(s float64) Point
- func (p Point) Normalize() Point
- func (p Point) Rotate(angle float64) Point
- func (p Point) Sub(q Point) Point
- type QuadBez
- func (q QuadBez) BoundingBox() Rect
- func (q QuadBez) End() Point
- func (q QuadBez) Eval(t float64) Point
- func (q QuadBez) Extrema() []float64
- func (q QuadBez) Raise() CubicBez
- func (q QuadBez) Start() Point
- func (q QuadBez) Subdivide() (QuadBez, QuadBez)
- func (q QuadBez) Subsegment(t0, t1 float64) QuadBez
- type QuadTo
- type RGBA
- type RadialGradientBrush
- type Rect
- type Renderer
- type SoftwareRenderer
- type SolidBrush
- type SolidPattern
- type Stroke
- func (s Stroke) Clone() Stroke
- func (s Stroke) IsDashed() bool
- func (s Stroke) WithCap(lineCap LineCap) Stroke
- func (s Stroke) WithDash(dash *Dash) Stroke
- func (s Stroke) WithDashOffset(offset float64) Stroke
- func (s Stroke) WithDashPattern(lengths ...float64) Stroke
- func (s Stroke) WithJoin(join LineJoin) Stroke
- func (s Stroke) WithMiterLimit(limit float64) Stroke
- func (s Stroke) WithWidth(w float64) Stroke
- type SweepGradientBrush
- type Vec2
- func (v Vec2) Add(w Vec2) Vec2
- func (v Vec2) Angle(w Vec2) float64
- func (v Vec2) Approx(w Vec2, epsilon float64) bool
- func (v Vec2) Atan2() float64
- func (v Vec2) Cross(w Vec2) float64
- func (v Vec2) Div(s float64) Vec2
- func (v Vec2) Dot(w Vec2) float64
- func (v Vec2) IsZero() bool
- func (v Vec2) Length() float64
- func (v Vec2) LengthSq() float64
- func (v Vec2) Lerp(w Vec2, t float64) Vec2
- func (v Vec2) Mul(s float64) Vec2
- func (v Vec2) Neg() Vec2
- func (v Vec2) Normalize() Vec2
- func (v Vec2) Perp() Vec2
- func (v Vec2) Rotate(angle float64) Vec2
- func (v Vec2) Sub(w Vec2) Vec2
- func (v Vec2) ToPoint() Point
Constants ¶
const ( // InterpNearest selects the closest pixel (no interpolation). // Fast but produces blocky results when scaling. InterpNearest = intImage.InterpNearest // InterpBilinear performs linear interpolation between 4 neighboring pixels. // Good balance between quality and performance. InterpBilinear = intImage.InterpBilinear // InterpBicubic performs cubic interpolation using a 4x4 pixel neighborhood. // Highest quality but slower than bilinear. InterpBicubic = intImage.InterpBicubic )
Image interpolation modes.
const ( // FormatGray8 is 8-bit grayscale (1 byte per pixel). FormatGray8 = intImage.FormatGray8 // FormatGray16 is 16-bit grayscale (2 bytes per pixel). FormatGray16 = intImage.FormatGray16 // FormatRGB8 is 24-bit RGB (3 bytes per pixel, no alpha). FormatRGB8 = intImage.FormatRGB8 // FormatRGBA8 is 32-bit RGBA in sRGB color space (4 bytes per pixel). // This is the standard format for most operations. FormatRGBA8 = intImage.FormatRGBA8 // FormatRGBAPremul is 32-bit RGBA with premultiplied alpha (4 bytes per pixel). // Used for correct alpha blending operations. FormatRGBAPremul = intImage.FormatRGBAPremul // FormatBGRA8 is 32-bit BGRA in sRGB color space (4 bytes per pixel). // Common on Windows and some GPU formats. FormatBGRA8 = intImage.FormatBGRA8 // FormatBGRAPremul is 32-bit BGRA with premultiplied alpha (4 bytes per pixel). FormatBGRAPremul = intImage.FormatBGRAPremul )
Pixel formats.
const ( // BlendNormal performs standard alpha blending (source over destination). BlendNormal = intImage.BlendNormal // BlendMultiply multiplies source and destination colors. // Result is always darker or equal. Formula: dst * src BlendMultiply = intImage.BlendMultiply // BlendScreen performs inverse multiply for lighter results. // Formula: 1 - (1-dst) * (1-src) BlendScreen = intImage.BlendScreen // BlendOverlay combines multiply and screen based on destination brightness. // Dark areas are multiplied, bright areas are screened. BlendOverlay = intImage.BlendOverlay )
Blend modes.
Variables ¶
var ( Black = RGB(0, 0, 0) White = RGB(1, 1, 1) Red = RGB(1, 0, 0) Green = RGB(0, 1, 0) Blue = RGB(0, 0, 1) Yellow = RGB(1, 1, 0) Cyan = RGB(0, 1, 1) Magenta = RGB(1, 0, 1) Transparent = RGBA2(0, 0, 0, 0) )
Common colors
Functions ¶
func SolveCubic ¶ added in v0.9.1
SolveCubic finds real roots of the cubic equation ax^3 + bx^2 + cx + d = 0. Returns roots (not necessarily sorted).
The implementation uses the method from: https://momentsingraphics.de/CubicRoots.html which is based on Jim Blinn's "How to Solve a Cubic Equation".
func SolveCubicInUnitInterval ¶ added in v0.9.1
SolveCubicInUnitInterval returns roots of ax^3 + bx^2 + cx + d = 0 that lie in [0, 1]. This is useful for finding parameter values on Bezier curves.
func SolveQuadratic ¶ added in v0.9.1
SolveQuadratic finds real roots of the quadratic equation ax^2 + bx + c = 0. Returns roots sorted in ascending order.
The function is numerically robust: - If a is zero or nearly zero, treats as linear equation - If all coefficients are zero, returns a single 0.0 - Handles edge cases with NaN and Inf gracefully
func SolveQuadraticInUnitInterval ¶ added in v0.9.1
SolveQuadraticInUnitInterval returns roots of ax^2 + bx + c = 0 that lie in [0, 1]. This is useful for finding parameter values on Bezier curves.
Types ¶
type BlendMode ¶ added in v0.3.0
BlendMode defines how source pixels are blended with destination pixels.
type Brush ¶ added in v0.12.0
type Brush interface {
// ColorAt returns the color at the given coordinates.
// For solid brushes, this returns the same color regardless of position.
// For pattern-based brushes, this samples the pattern at (x, y).
ColorAt(x, y float64) RGBA
// contains filtered or unexported methods
}
Brush represents what to paint with. This is a sealed interface - only types in this package implement it.
The Brush pattern follows vello/peniko Rust conventions, providing a type-safe way to represent different brush types (solid colors, gradients, images) while maintaining extensibility through CustomBrush.
Supported brush types:
- SolidBrush: A single solid color
- CustomBrush: User-defined color function (see brush_custom.go)
Example usage:
// Using convenience constructors
ctx.SetFillBrush(gg.Solid(gg.Red))
ctx.SetStrokeBrush(gg.SolidRGB(0.5, 0.5, 0.5))
// Using hex colors
brush := gg.SolidHex("#FF5733")
func BrushFromPattern
deprecated
added in
v0.12.0
BrushFromPattern converts a legacy Pattern to a Brush. This is a compatibility helper for migrating from Pattern to Brush.
If the pattern is a SolidPattern, it returns a SolidBrush. Otherwise, it wraps the pattern in a CustomBrush.
Deprecated: Use Brush types directly instead of Pattern.
type ColorFunc ¶ added in v0.12.0
ColorFunc is a function that returns a color at a given position. Used by CustomBrush to define custom brush patterns.
type ColorStop ¶ added in v0.12.0
type ColorStop struct {
Offset float64 // Position in gradient, 0.0 to 1.0
Color RGBA // Color at this position
}
ColorStop represents a color at a specific position in a gradient.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is the main drawing context. It maintains a pixmap, current path, paint state, and transformation stack. Context implements io.Closer for proper resource cleanup.
func NewContext ¶
NewContext creates a new drawing context with the given dimensions.
func NewContextForImage ¶
NewContextForImage creates a context for drawing on an existing image.
func (*Context) AsMask ¶ added in v0.14.0
AsMask creates a mask from the current path. The mask is filled according to the current fill rule. The path is NOT cleared after this operation.
func (*Context) ClearDash ¶ added in v0.12.0
func (c *Context) ClearDash()
ClearDash removes the dash pattern, returning to solid lines.
func (*Context) ClearMask ¶ added in v0.14.0
func (c *Context) ClearMask()
ClearMask removes the current mask.
func (*Context) ClearWithColor ¶
ClearWithColor fills the entire context with a specific color.
func (*Context) Clip ¶ added in v0.3.0
func (c *Context) Clip()
Clip sets the current path as the clipping region and clears the path. Subsequent drawing operations will be clipped to this region. The clip region is intersected with any existing clip regions.
func (*Context) ClipPreserve ¶ added in v0.3.0
func (c *Context) ClipPreserve()
ClipPreserve sets the current path as the clipping region but keeps the path. This is like Clip() but doesn't clear the path, allowing you to both clip and then fill/stroke the same path.
func (*Context) ClipRect ¶ added in v0.3.0
ClipRect sets a rectangular clipping region. This is a faster alternative to creating a rectangular path and calling Clip(). The clip region is intersected with any existing clip regions.
func (*Context) Close ¶ added in v0.14.0
Close releases resources associated with the Context. After Close, the Context should not be used. Close is idempotent - multiple calls are safe. Implements io.Closer.
func (*Context) CreateImagePattern ¶ added in v0.3.0
CreateImagePattern creates an image pattern from a rectangular region of an image. The pattern can be used with SetFillPattern or SetStrokePattern.
Example:
img, _ := gg.LoadImage("texture.png")
pattern := dc.CreateImagePattern(img, 0, 0, 100, 100)
dc.SetFillPattern(pattern)
dc.DrawRectangle(0, 0, 400, 300)
dc.Fill()
func (*Context) DrawCircle ¶
DrawCircle draws a circle.
func (*Context) DrawEllipse ¶
DrawEllipse draws an ellipse.
func (*Context) DrawEllipticalArc ¶
DrawEllipticalArc draws an elliptical arc (advanced).
func (*Context) DrawImage ¶ added in v0.3.0
DrawImage draws an image at the specified position. The current transformation matrix is applied to the position and size.
Example:
img, _ := gg.LoadImage("photo.png")
dc.DrawImage(img, 100, 100)
func (*Context) DrawImageEx ¶ added in v0.3.0
func (c *Context) DrawImageEx(img *ImageBuf, opts DrawImageOptions)
DrawImageEx draws an image with advanced options. The current transformation matrix is applied to the position and size.
Example:
dc.DrawImageEx(img, gg.DrawImageOptions{
X: 100,
Y: 100,
DstWidth: 200,
DstHeight: 150,
Interpolation: gg.InterpBicubic,
Opacity: 0.8,
BlendMode: gg.BlendNormal,
})
func (*Context) DrawRectangle ¶
DrawRectangle draws a rectangle.
func (*Context) DrawRegularPolygon ¶
DrawRegularPolygon draws a regular polygon with n sides.
func (*Context) DrawRoundedRectangle ¶
DrawRoundedRectangle draws a rectangle with rounded corners.
func (*Context) DrawString ¶
DrawString draws text at position (x, y) where y is the baseline. If no font has been set with SetFont, this function does nothing.
The baseline is the line on which most letters sit. Characters with descenders (like 'g', 'j', 'p', 'q', 'y') extend below the baseline.
func (*Context) DrawStringAnchored ¶
DrawStringAnchored draws text with an anchor point. The anchor point is specified by ax and ay, which are in the range [0, 1].
(0, 0) = top-left (0.5, 0.5) = center (1, 1) = bottom-right
The text is positioned so that the anchor point is at (x, y).
func (*Context) EncodeJPEG ¶ added in v0.14.0
EncodeJPEG writes the image as JPEG with the given quality (1-100).
func (*Context) EncodePNG ¶ added in v0.14.0
EncodePNG writes the image as PNG to the given writer. This is useful for streaming, network output, or custom storage.
func (*Context) FillPreserve ¶
func (c *Context) FillPreserve()
FillPreserve fills the current path and preserves it for additional operations.
func (*Context) Font ¶ added in v0.2.0
Font returns the current font face. Returns nil if no font has been set.
func (*Context) GetCurrentPoint ¶ added in v0.14.0
GetCurrentPoint returns the current point of the path. Returns (0, 0, false) if there is no current point.
func (*Context) GetMask ¶ added in v0.14.0
GetMask returns the current mask, or nil if no mask is set.
func (*Context) Identity ¶
func (c *Context) Identity()
Identity resets the transformation matrix to identity.
func (*Context) InvertMask ¶ added in v0.14.0
func (c *Context) InvertMask()
InvertMask inverts the current mask. Has no effect if no mask is set.
func (*Context) InvertY ¶
func (c *Context) InvertY()
InvertY inverts the Y axis (useful for coordinate system changes).
func (*Context) IsDashed ¶ added in v0.12.0
IsDashed returns true if the current stroke uses a dash pattern.
func (*Context) LoadFontFace
deprecated
LoadFontFace loads a font from a file and sets it as the current font. The size is specified in points.
Deprecated: Use text.NewFontSourceFromFile and SetFont instead. This method is provided for convenience and backward compatibility.
Example (new way):
source, err := text.NewFontSourceFromFile("font.ttf")
if err != nil {
return err
}
face := source.Face(12.0)
ctx.SetFont(face)
func (*Context) MeasureString ¶
MeasureString returns the dimensions of text in pixels. Returns (width, height) where:
- width is the horizontal advance of the text
- height is the line height (ascent + descent + line gap)
If no font has been set, returns (0, 0).
func (*Context) NewSubPath ¶
func (c *Context) NewSubPath()
NewSubPath starts a new subpath without closing the previous one.
func (*Context) PopLayer ¶ added in v0.4.0
func (c *Context) PopLayer()
PopLayer composites the current layer onto the parent layer/canvas. Uses the blend mode and opacity specified in the corresponding PushLayer call.
The layer is composited using the specified blend mode and opacity. After compositing, the layer's memory is returned to the pool for reuse.
If there are no layers to pop, this function does nothing.
Example:
dc.PushLayer(gg.BlendScreen, 1.0) // ... draw operations ... dc.PopLayer() // Composite layer onto parent
func (*Context) Push ¶
func (c *Context) Push()
Push saves the current state (transform, paint, clip, and mask).
func (*Context) PushLayer ¶ added in v0.4.0
PushLayer creates a new layer and makes it the active drawing target. All subsequent drawing operations will render to this layer until PopLayer is called.
The layer will be composited onto the parent layer/canvas when PopLayer is called, using the specified blend mode and opacity.
Parameters:
- blendMode: How to composite this layer onto the parent (e.g., BlendMultiply, BlendScreen)
- opacity: Layer opacity in range [0.0, 1.0] where 0 is fully transparent and 1 is fully opaque
Example:
dc.PushLayer(gg.BlendMultiply, 0.5) dc.SetRGB(1, 0, 0) dc.DrawCircle(100, 100, 50) dc.Fill() dc.PopLayer() // Composite circle onto canvas with multiply blend at 50% opacity
func (*Context) QuadraticTo ¶
QuadraticTo adds a quadratic Bezier curve to the current path.
func (*Context) ResetClip ¶ added in v0.3.0
func (c *Context) ResetClip()
ResetClip removes all clipping regions, restoring the full canvas as drawable.
func (*Context) RotateAbout ¶
RotateAbout rotates around a specific point.
func (*Context) SetBlendMode ¶ added in v0.4.0
SetBlendMode sets the blend mode for subsequent fill and stroke operations. This is currently a placeholder for future blend mode support in direct drawing operations.
For now, blend modes are primarily used with layers via PushLayer/PopLayer.
Example:
dc.SetBlendMode(gg.BlendMultiply) dc.Fill() // Future: will use multiply blend mode
func (*Context) SetDash ¶ added in v0.12.0
SetDash sets the dash pattern for stroking. Pass alternating dash and gap lengths. Passing no arguments clears the dash pattern (returns to solid lines).
Example:
ctx.SetDash(5, 3) // 5 units dash, 3 units gap ctx.SetDash(10, 5, 2, 5) // complex pattern ctx.SetDash() // clear dash (solid line)
func (*Context) SetDashOffset ¶ added in v0.12.0
SetDashOffset sets the starting offset into the dash pattern. This has no effect if no dash pattern is set.
func (*Context) SetFillBrush ¶ added in v0.12.0
SetFillBrush sets the brush used for fill operations. This is the preferred way to set fill styling in new code.
Example:
ctx.SetFillBrush(gg.Solid(gg.Red))
ctx.SetFillBrush(gg.SolidHex("#FF5733"))
ctx.SetFillBrush(gg.HorizontalGradient(gg.Red, gg.Blue, 0, 100))
func (*Context) SetFillPattern ¶ added in v0.3.0
SetFillPattern sets the fill pattern.
func (*Context) SetFillRule ¶
SetFillRule sets the fill rule.
func (*Context) SetFont ¶ added in v0.2.0
SetFont sets the current font face for text drawing. The face should be created from a FontSource.
Example:
source, _ := text.NewFontSourceFromFile("font.ttf")
face := source.Face(12.0)
ctx.SetFont(face)
func (*Context) SetHexColor ¶
SetHexColor sets the current color using a hex string.
func (*Context) SetLineCap ¶
SetLineCap sets the line cap style.
func (*Context) SetLineJoin ¶
SetLineJoin sets the line join style.
func (*Context) SetLineWidth ¶
SetLineWidth sets the line width for stroking.
func (*Context) SetMask ¶ added in v0.14.0
SetMask sets an alpha mask for subsequent drawing operations. The mask modulates the alpha of all drawing operations. Pass nil to clear the mask.
func (*Context) SetMiterLimit ¶ added in v0.12.0
SetMiterLimit sets the miter limit for line joins.
func (*Context) SetStroke ¶ added in v0.12.0
SetStroke sets the complete stroke style. This is the preferred way to configure stroke properties.
Example:
ctx.SetStroke(gg.DefaultStroke().WithWidth(2).WithCap(gg.LineCapRound)) ctx.SetStroke(gg.DashedStroke(5, 3))
func (*Context) SetStrokeBrush ¶ added in v0.12.0
SetStrokeBrush sets the brush used for stroke operations. Note: In the current implementation, fill and stroke share the same brush. This method is provided for API symmetry and future extensibility.
Example:
ctx.SetStrokeBrush(gg.Solid(gg.Black)) ctx.SetStrokeBrush(gg.SolidRGB(0.5, 0.5, 0.5))
func (*Context) SetStrokePattern ¶ added in v0.3.0
SetStrokePattern sets the stroke pattern.
func (*Context) StrokeBrush ¶ added in v0.12.0
StrokeBrush returns the current stroke brush. Note: In the current implementation, fill and stroke share the same brush.
func (*Context) StrokePreserve ¶
func (c *Context) StrokePreserve()
StrokePreserve strokes the current path and preserves it.
func (*Context) TransformPoint ¶
TransformPoint transforms a point by the current matrix.
type CubicBez ¶ added in v0.9.1
type CubicBez struct {
P0, P1, P2, P3 Point
}
CubicBez represents a cubic Bezier curve with control points P0, P1, P2, P3. P0 is the start point, P1 and P2 are control points, P3 is the end point.
func NewCubicBez ¶ added in v0.9.1
NewCubicBez creates a new cubic Bezier curve.
func (CubicBez) BoundingBox ¶ added in v0.9.1
BoundingBox returns the tight axis-aligned bounding box of the curve.
func (CubicBez) Deriv ¶ added in v0.9.1
Deriv returns the derivative curve (a quadratic Bezier). The derivative gives the tangent direction at any point.
func (CubicBez) Eval ¶ added in v0.9.1
Eval evaluates the curve at parameter t (0 to 1) using de Casteljau's algorithm.
func (CubicBez) Extrema ¶ added in v0.9.1
Extrema returns parameter values where the derivative is zero (extrema points). For a cubic Bezier, there can be up to 4 extrema (2 for x, 2 for y).
func (CubicBez) Inflections ¶ added in v0.9.1
Inflections returns the parameter values of inflection points. An inflection point is where the curvature changes sign. A cubic can have 0, 1, or 2 inflection points.
func (CubicBez) Normal ¶ added in v0.9.1
Normal returns the normal vector (perpendicular to tangent) at parameter t.
func (CubicBez) Subdivide ¶ added in v0.9.1
Subdivide splits the curve at t=0.5 into two halves using de Casteljau.
func (CubicBez) Subsegment ¶ added in v0.9.1
Subsegment returns the portion of the curve from t0 to t1.
type CustomBrush ¶ added in v0.12.0
type CustomBrush struct {
// Func is the color function that determines the color at each point.
Func ColorFunc
// Name is an optional identifier for debugging and logging.
Name string
}
CustomBrush is a brush with a user-defined color function. It allows for arbitrary patterns, gradients, and procedural textures.
CustomBrush implements the Brush interface, making it compatible with all brush-based operations.
Example:
// Create a checkerboard pattern
checker := gg.NewCustomBrush(func(x, y float64) gg.RGBA {
if (int(x/10)+int(y/10))%2 == 0 {
return gg.Black
}
return gg.White
})
func Checkerboard ¶ added in v0.12.0
func Checkerboard(c0, c1 RGBA, size float64) CustomBrush
Checkerboard creates a checkerboard pattern brush. size is the size of each square in pixels.
Example:
checker := gg.Checkerboard(gg.Black, gg.White, 10)
func HorizontalGradient ¶ added in v0.12.0
func HorizontalGradient(c0, c1 RGBA, x0, x1 float64) CustomBrush
HorizontalGradient creates a linear gradient from left to right. x0 and x1 define the gradient range in pixel coordinates.
Example:
gradient := gg.HorizontalGradient(gg.Red, gg.Blue, 0, 100)
func LinearGradient ¶ added in v0.12.0
func LinearGradient(c0, c1 RGBA, x0, y0, x1, y1 float64) CustomBrush
LinearGradient creates a linear gradient along an arbitrary line. The gradient is defined from point (x0, y0) to point (x1, y1).
Example:
// Diagonal gradient from top-left to bottom-right gradient := gg.LinearGradient(gg.Red, gg.Blue, 0, 0, 100, 100)
func NewCustomBrush ¶ added in v0.12.0
func NewCustomBrush(fn ColorFunc) CustomBrush
NewCustomBrush creates a CustomBrush from a color function.
Example:
// Horizontal gradient from red to blue
gradient := gg.NewCustomBrush(func(x, y float64) gg.RGBA {
t := x / 100.0 // Assuming 100px width
return gg.Red.Lerp(gg.Blue, t)
})
func RadialGradient ¶ added in v0.12.0
func RadialGradient(c0, c1 RGBA, cx, cy, r float64) CustomBrush
RadialGradient creates a radial gradient from center outward. The gradient is defined from the center (cx, cy) with radius r. c0 is the center color, c1 is the edge color.
Example:
// White center fading to black at radius 50 gradient := gg.RadialGradient(gg.White, gg.Black, 50, 50, 50)
func Stripes ¶ added in v0.12.0
func Stripes(c0, c1 RGBA, width, angle float64) CustomBrush
Stripes creates a striped pattern brush. width is the stripe width, angle is the rotation in radians.
Example:
// Vertical stripes stripes := gg.Stripes(gg.Red, gg.White, 10, 0) // Diagonal stripes (45 degrees) diag := gg.Stripes(gg.Blue, gg.Yellow, 10, math.Pi/4)
func VerticalGradient ¶ added in v0.12.0
func VerticalGradient(c0, c1 RGBA, y0, y1 float64) CustomBrush
VerticalGradient creates a linear gradient from top to bottom. y0 and y1 define the gradient range in pixel coordinates.
Example:
gradient := gg.VerticalGradient(gg.White, gg.Black, 0, 100)
func (CustomBrush) ColorAt ¶ added in v0.12.0
func (b CustomBrush) ColorAt(x, y float64) RGBA
ColorAt implements Brush. Returns the color from the custom function.
func (CustomBrush) WithName ¶ added in v0.12.0
func (b CustomBrush) WithName(name string) CustomBrush
WithName returns a new CustomBrush with the specified name. Useful for debugging and logging.
Example:
brush := gg.NewCustomBrush(myFunc).WithName("myPattern")
type Dash ¶ added in v0.12.0
type Dash struct {
// Array contains alternating dash/gap lengths.
// If the array has an odd number of elements, it is logically duplicated
// to create an even-length pattern (e.g., [5] becomes [5, 5]).
Array []float64
// Offset is the starting offset into the pattern.
// The stroke begins at this point in the pattern cycle.
Offset float64
}
Dash defines a dash pattern for stroking. A dash pattern consists of alternating dash and gap lengths. For example, [5, 3] creates a pattern of 5 units dash, 3 units gap.
func NewDash ¶ added in v0.12.0
NewDash creates a dash pattern from alternating dash/gap lengths. If an odd number of elements is provided, the pattern is conceptually duplicated to create an even-length pattern.
Examples:
NewDash(5, 3) // 5 units dash, 3 units gap NewDash(10, 5, 2, 5) // 10 dash, 5 gap, 2 dash, 5 gap NewDash(5) // equivalent to [5, 5]
Returns nil if no lengths are provided or all lengths are zero.
func (*Dash) IsDashed ¶ added in v0.12.0
IsDashed returns true if this represents a dashed line (not solid). Returns false for nil Dash or empty/all-zero arrays.
func (*Dash) NormalizedOffset ¶ added in v0.12.0
NormalizedOffset returns the offset normalized to be within one pattern cycle. This is useful for calculating where in the pattern a stroke should begin.
func (*Dash) PatternLength ¶ added in v0.12.0
PatternLength returns the total length of one complete pattern cycle. For odd-length arrays, this includes the duplicated pattern.
func (*Dash) WithOffset ¶ added in v0.12.0
WithOffset returns a new Dash with the given offset. The offset determines where in the pattern the stroke begins.
type DrawImageOptions ¶ added in v0.3.0
type DrawImageOptions struct {
// X, Y specify the top-left corner where the image will be drawn.
X, Y float64
// DstWidth and DstHeight specify the dimensions to scale the image to.
// If zero, the source dimensions are used (possibly from SrcRect).
DstWidth float64
DstHeight float64
// SrcRect defines the source rectangle to sample from.
// If nil, the entire source image is used.
SrcRect *image.Rectangle
// Interpolation specifies the interpolation mode for sampling.
// Default is InterpBilinear.
Interpolation InterpolationMode
// Opacity controls the overall transparency of the source image (0.0 to 1.0).
// 1.0 means fully opaque, 0.0 means fully transparent.
// Default is 1.0.
Opacity float64
// BlendMode specifies how to blend source and destination pixels.
// Default is BlendNormal.
BlendMode BlendMode
}
DrawImageOptions specifies parameters for drawing an image.
type ExtendMode ¶ added in v0.12.0
type ExtendMode int
ExtendMode defines how gradients extend beyond their defined bounds.
const ( // ExtendPad extends edge colors beyond bounds (default behavior). ExtendPad ExtendMode = iota // ExtendRepeat repeats the gradient pattern. ExtendRepeat // ExtendReflect mirrors the gradient pattern. ExtendReflect )
type FillRule ¶
type FillRule int
FillRule specifies how to determine which areas are inside a path.
type ImageBuf ¶ added in v0.3.0
ImageBuf is a public alias for internal ImageBuf. It represents a memory-efficient image buffer with support for multiple pixel formats and lazy premultiplication.
func ImageBufFromImage ¶ added in v0.3.0
ImageBufFromImage creates an ImageBuf from a standard image.Image.
func LoadImage ¶ added in v0.3.0
LoadImage loads an image from a file and returns an ImageBuf. Supported formats: PNG, JPEG, GIF.
func NewImageBuf ¶ added in v0.3.0
func NewImageBuf(width, height int, format ImageFormat) (*ImageBuf, error)
NewImageBuf creates a new image buffer with the given dimensions and format.
type ImageFormat ¶ added in v0.3.0
ImageFormat represents a pixel storage format.
type ImagePattern ¶ added in v0.3.0
type ImagePattern struct {
// contains filtered or unexported fields
}
ImagePattern represents an image-based pattern.
func (*ImagePattern) ColorAt ¶ added in v0.3.0
func (p *ImagePattern) ColorAt(x, y float64) RGBA
ColorAt implements the Pattern interface. It samples the image at the given coordinates using wrapping/tiling behavior.
type InterpolationMode ¶ added in v0.3.0
type InterpolationMode = intImage.InterpolationMode
InterpolationMode defines how texture sampling is performed when drawing images.
type Layer ¶ added in v0.4.0
type Layer struct {
// contains filtered or unexported fields
}
Layer represents a drawing layer with blend mode and opacity. Layers allow isolating drawing operations and compositing them with different blend modes and opacity values, similar to layers in Photoshop or SVG group opacity.
type Line ¶ added in v0.9.1
type Line struct {
P0, P1 Point
}
Line represents a line segment from P0 to P1.
func (Line) BoundingBox ¶ added in v0.9.1
BoundingBox returns the axis-aligned bounding box of the line.
func (Line) Eval ¶ added in v0.9.1
Eval evaluates the line at parameter t (0 to 1). t=0 returns P0, t=1 returns P1.
func (Line) Subsegment ¶ added in v0.9.1
Subsegment returns the portion of the line from t0 to t1.
type LinearGradientBrush ¶ added in v0.12.0
type LinearGradientBrush struct {
Start Point // Start point of the gradient
End Point // End point of the gradient
Stops []ColorStop // Color stops defining the gradient
Extend ExtendMode // How gradient extends beyond bounds
}
LinearGradientBrush represents a linear color transition between two points. It implements the Brush interface and supports multiple color stops, proper sRGB color interpolation, and configurable extend modes.
LinearGradientBrush follows the vello/peniko gradient model, providing professional-quality gradients for 2D graphics.
Example:
gradient := gg.NewLinearGradientBrush(0, 0, 100, 0).
AddColorStop(0, gg.Red).
AddColorStop(0.5, gg.Yellow).
AddColorStop(1, gg.Blue)
ctx.SetFillBrush(gradient)
func NewLinearGradientBrush ¶ added in v0.12.0
func NewLinearGradientBrush(x0, y0, x1, y1 float64) *LinearGradientBrush
NewLinearGradientBrush creates a new linear gradient from (x0, y0) to (x1, y1).
func (*LinearGradientBrush) AddColorStop ¶ added in v0.12.0
func (g *LinearGradientBrush) AddColorStop(offset float64, c RGBA) *LinearGradientBrush
AddColorStop adds a color stop at the specified offset. Offset should be in the range [0, 1]. Returns the gradient for method chaining.
func (*LinearGradientBrush) ColorAt ¶ added in v0.12.0
func (g *LinearGradientBrush) ColorAt(x, y float64) RGBA
ColorAt returns the color at the given point. Implements the Pattern and Brush interfaces.
func (*LinearGradientBrush) SetExtend ¶ added in v0.12.0
func (g *LinearGradientBrush) SetExtend(mode ExtendMode) *LinearGradientBrush
SetExtend sets the extend mode for the gradient. Returns the gradient for method chaining.
type Mask ¶ added in v0.14.0
type Mask struct {
// contains filtered or unexported fields
}
Mask represents an alpha mask for compositing operations. Values range from 0 (fully transparent) to 255 (fully opaque).
func NewMask ¶ added in v0.14.0
NewMask creates a new empty mask with the given dimensions. All values are initialized to 0 (fully transparent).
func NewMaskFromAlpha ¶ added in v0.14.0
NewMaskFromAlpha creates a mask from an image's alpha channel.
func (*Mask) At ¶ added in v0.14.0
At returns the mask value at (x, y). Returns 0 for coordinates outside the mask bounds.
func (*Mask) Clear ¶ added in v0.14.0
func (m *Mask) Clear()
Clear clears the mask (sets all values to 0).
func (*Mask) Data ¶ added in v0.14.0
Data returns the underlying mask data slice. This is useful for advanced operations.
func (*Mask) Invert ¶ added in v0.14.0
func (m *Mask) Invert()
Invert inverts all mask values (255 - value).
type Matrix ¶
Matrix represents a 2D affine transformation matrix. It uses a 2x3 matrix in row-major order:
| a b c | | d e f |
This represents the transformation:
x' = a*x + b*y + c y' = d*x + e*y + f
func (Matrix) Invert ¶
Invert returns the inverse matrix. Returns the identity matrix if the matrix is not invertible.
func (Matrix) IsIdentity ¶
IsIdentity returns true if the matrix is the identity matrix.
func (Matrix) IsTranslation ¶
IsTranslation returns true if the matrix is only a translation.
func (Matrix) TransformPoint ¶
TransformPoint applies the transformation to a point.
func (Matrix) TransformVector ¶
TransformVector applies the transformation to a vector (no translation).
type Paint ¶
type Paint struct {
// Pattern is the fill or stroke pattern.
//
// Deprecated: Use Brush instead. Pattern is maintained for backward compatibility.
Pattern Pattern
// Brush is the fill or stroke brush (vello/peniko pattern).
// When both Brush and Pattern are set, Brush takes precedence.
// Use SetBrush() to set the brush, which also updates Pattern for compatibility.
Brush Brush
// LineWidth is the width of strokes.
//
// Deprecated: Use Stroke.Width instead. Maintained for backward compatibility.
LineWidth float64
// LineCap is the shape of line endpoints.
//
// Deprecated: Use Stroke.Cap instead. Maintained for backward compatibility.
LineCap LineCap
// LineJoin is the shape of line joins.
//
// Deprecated: Use Stroke.Join instead. Maintained for backward compatibility.
LineJoin LineJoin
// MiterLimit is the miter limit for sharp joins.
//
// Deprecated: Use Stroke.MiterLimit instead. Maintained for backward compatibility.
MiterLimit float64
// FillRule is the fill rule for paths
FillRule FillRule
// Antialias enables anti-aliasing
Antialias bool
// Stroke is the unified stroke style configuration.
// This is the preferred way to configure stroke properties.
// When Stroke is set, it takes precedence over the individual
// LineWidth, LineCap, LineJoin, and MiterLimit fields.
Stroke *Stroke
}
Paint represents the styling information for drawing.
func (*Paint) ColorAt ¶ added in v0.12.0
ColorAt returns the color at the given position. It uses Brush if set, otherwise falls back to Pattern.
func (*Paint) EffectiveDash ¶ added in v0.12.0
EffectiveDash returns the effective dash pattern. Returns nil if no dash is set (solid line).
func (*Paint) EffectiveLineCap ¶ added in v0.12.0
EffectiveLineCap returns the effective line cap. If Stroke is set, uses Stroke.Cap; otherwise uses LineCap.
func (*Paint) EffectiveLineJoin ¶ added in v0.12.0
EffectiveLineJoin returns the effective line join. If Stroke is set, uses Stroke.Join; otherwise uses LineJoin.
func (*Paint) EffectiveLineWidth ¶ added in v0.12.0
EffectiveLineWidth returns the effective line width. If Stroke is set, uses Stroke.Width; otherwise uses LineWidth.
func (*Paint) EffectiveMiterLimit ¶ added in v0.12.0
EffectiveMiterLimit returns the effective miter limit. If Stroke is set, uses Stroke.MiterLimit; otherwise uses MiterLimit.
func (*Paint) GetBrush ¶ added in v0.12.0
GetBrush returns the current brush. If Brush is nil, it returns a brush converted from Pattern.
func (*Paint) GetStroke ¶ added in v0.12.0
GetStroke returns the effective stroke style. If Stroke is set, returns a copy of it. Otherwise, constructs a Stroke from the legacy fields.
func (*Paint) IsDashed ¶ added in v0.12.0
IsDashed returns true if the current stroke uses a dash pattern.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path represents a vector path.
func (*Path) Arc ¶
Arc adds a circular arc to the path. The arc is drawn from angle1 to angle2 (in radians) around center (cx, cy).
func (*Path) Area ¶ added in v0.9.1
Area returns the signed area enclosed by the path. Positive for clockwise paths, negative for counter-clockwise. Uses the shoelace formula extended for curves (Green's theorem). Only closed subpaths contribute to the area.
func (*Path) BoundingBox ¶ added in v0.9.1
BoundingBox returns the tight axis-aligned bounding box of the path. Uses curve extrema for accuracy.
func (*Path) Close ¶
func (p *Path) Close()
Close closes the current subpath by drawing a line to the start point.
func (*Path) Contains ¶ added in v0.9.1
Contains tests if a point is inside the path using the non-zero fill rule.
func (*Path) CurrentPoint ¶
CurrentPoint returns the current point.
func (*Path) Flatten ¶ added in v0.9.1
Flatten converts all curves to line segments with given tolerance. tolerance is the maximum distance from the curve.
func (*Path) FlattenCallback ¶ added in v0.9.1
FlattenCallback calls fn for each point in the flattened path. More efficient than Flatten() as it avoids allocation.
func (*Path) HasCurrentPoint ¶ added in v0.14.0
HasCurrentPoint returns true if the path has a current point. A path has a current point after MoveTo, LineTo, or any curve operation.
func (*Path) Length ¶ added in v0.9.1
Length returns the total arc length of the path. accuracy controls the precision of the approximation (smaller = more accurate).
func (*Path) QuadraticTo ¶
QuadraticTo draws a quadratic Bezier curve.
func (*Path) Reversed ¶ added in v0.9.1
Reversed returns a new path with reversed direction. Each subpath is reversed independently.
func (*Path) RoundedRectangle ¶
RoundedRectangle adds a rectangle with rounded corners.
type PathBuilder ¶ added in v0.14.0
type PathBuilder struct {
// contains filtered or unexported fields
}
PathBuilder provides a fluent interface for path construction. All methods return the builder for chaining.
func BuildPath ¶ added in v0.14.0
func BuildPath() *PathBuilder
BuildPath starts a new path builder.
func (*PathBuilder) Build ¶ added in v0.14.0
func (b *PathBuilder) Build() *Path
Build returns the constructed path.
func (*PathBuilder) Circle ¶ added in v0.14.0
func (b *PathBuilder) Circle(cx, cy, r float64) *PathBuilder
Circle adds a circle to the path.
func (*PathBuilder) Close ¶ added in v0.14.0
func (b *PathBuilder) Close() *PathBuilder
Close closes the current subpath.
func (*PathBuilder) CubicTo ¶ added in v0.14.0
func (b *PathBuilder) CubicTo(c1x, c1y, c2x, c2y, x, y float64) *PathBuilder
CubicTo draws a cubic Bezier curve.
func (*PathBuilder) Ellipse ¶ added in v0.14.0
func (b *PathBuilder) Ellipse(cx, cy, rx, ry float64) *PathBuilder
Ellipse adds an ellipse to the path.
func (*PathBuilder) LineTo ¶ added in v0.14.0
func (b *PathBuilder) LineTo(x, y float64) *PathBuilder
LineTo draws a line to a position.
func (*PathBuilder) MoveTo ¶ added in v0.14.0
func (b *PathBuilder) MoveTo(x, y float64) *PathBuilder
MoveTo moves to a new position.
func (*PathBuilder) Path ¶ added in v0.14.0
func (b *PathBuilder) Path() *Path
Path returns the constructed path (alias for Build).
func (*PathBuilder) Polygon ¶ added in v0.14.0
func (b *PathBuilder) Polygon(cx, cy, radius float64, sides int) *PathBuilder
Polygon adds a regular polygon to the path.
func (*PathBuilder) QuadTo ¶ added in v0.14.0
func (b *PathBuilder) QuadTo(cx, cy, x, y float64) *PathBuilder
QuadTo draws a quadratic Bezier curve.
func (*PathBuilder) Rect ¶ added in v0.14.0
func (b *PathBuilder) Rect(x, y, w, h float64) *PathBuilder
Rect adds a rectangle to the path.
func (*PathBuilder) RoundRect ¶ added in v0.14.0
func (b *PathBuilder) RoundRect(x, y, w, h, r float64) *PathBuilder
RoundRect adds a rounded rectangle to the path.
func (*PathBuilder) Star ¶ added in v0.14.0
func (b *PathBuilder) Star(cx, cy, outerRadius, innerRadius float64, points int) *PathBuilder
Star adds a star shape to the path.
type PathElement ¶
type PathElement interface {
// contains filtered or unexported methods
}
PathElement represents a single element in a path.
type Pattern ¶
type Pattern interface {
// ColorAt returns the color at the given point.
ColorAt(x, y float64) RGBA
}
Pattern represents a fill or stroke pattern.
func PatternFromBrush
deprecated
added in
v0.12.0
type Pixmap ¶
type Pixmap struct {
// contains filtered or unexported fields
}
Pixmap represents a rectangular pixel buffer. It implements both image.Image (read-only) and draw.Image (read-write) interfaces, making it compatible with Go's standard image ecosystem including text rendering via golang.org/x/image/font.
func (*Pixmap) ColorModel ¶
ColorModel implements the image.Image interface.
func (*Pixmap) EncodeJPEG ¶ added in v0.14.0
EncodeJPEG writes the pixmap as JPEG with the given quality (1-100).
func (*Pixmap) EncodePNG ¶ added in v0.14.0
EncodePNG writes the pixmap as PNG to the given writer. This is useful for streaming, network output, or custom storage.
func (*Pixmap) FillSpan ¶ added in v0.5.0
FillSpan fills a horizontal span of pixels with a solid color (no blending). This is optimized for batch operations when the span is >= 16 pixels. The span is from x1 (inclusive) to x2 (exclusive) on row y.
func (*Pixmap) FillSpanBlend ¶ added in v0.5.0
FillSpanBlend fills a horizontal span with blending. This uses batch blending operations for spans >= 16 pixels.
func (*Pixmap) Set ¶ added in v0.9.1
Set implements the draw.Image interface. This allows Pixmap to be used as a destination for image drawing operations, including text rendering via golang.org/x/image/font.
type Point ¶
type Point struct {
X, Y float64
}
Point represents a 2D point or vector.
func (Point) LengthSquared ¶
LengthSquared returns the squared length of the vector.
func (Point) Lerp ¶
Lerp performs linear interpolation between two points. t=0 returns p, t=1 returns q, intermediate values interpolate.
type QuadBez ¶ added in v0.9.1
type QuadBez struct {
P0, P1, P2 Point
}
QuadBez represents a quadratic Bezier curve with control points P0, P1, P2. P0 is the start point, P1 is the control point, P2 is the end point.
func NewQuadBez ¶ added in v0.9.1
NewQuadBez creates a new quadratic Bezier curve.
func (QuadBez) BoundingBox ¶ added in v0.9.1
BoundingBox returns the tight axis-aligned bounding box of the curve.
func (QuadBez) Eval ¶ added in v0.9.1
Eval evaluates the curve at parameter t (0 to 1) using de Casteljau's algorithm.
func (QuadBez) Extrema ¶ added in v0.9.1
Extrema returns parameter values where the derivative is zero (extrema points). Used for computing tight bounding boxes.
func (QuadBez) Raise ¶ added in v0.9.1
Raise elevates the quadratic to a cubic Bezier curve. Returns an exact cubic representation of this quadratic.
func (QuadBez) Subdivide ¶ added in v0.9.1
Subdivide splits the curve at t=0.5 into two halves using de Casteljau.
func (QuadBez) Subsegment ¶ added in v0.9.1
Subsegment returns the portion of the curve from t0 to t1.
type RGBA ¶
type RGBA struct {
R, G, B, A float64
}
RGBA represents a color with red, green, blue, and alpha components. Each component is in the range [0, 1].
func HSL ¶
HSL creates a color from HSL values. h is hue [0, 360), s is saturation [0, 1], l is lightness [0, 1].
func Hex ¶
Hex creates a color from a hex string. Supports formats: "RGB", "RGBA", "RRGGBB", "RRGGBBAA".
func (RGBA) Premultiply ¶
Premultiply returns a premultiplied color.
func (RGBA) Unpremultiply ¶
Unpremultiply returns an unpremultiplied color.
type RadialGradientBrush ¶ added in v0.12.0
type RadialGradientBrush struct {
Center Point // Center of the gradient circle
Focus Point // Focal point (can differ from center)
StartRadius float64 // Inner radius where gradient begins (t=0)
EndRadius float64 // Outer radius where gradient ends (t=1)
Stops []ColorStop // Color stops defining the gradient
Extend ExtendMode // How gradient extends beyond bounds
}
RadialGradientBrush represents a radial color transition. Colors radiate from a focal point within a circle defined by center and end radius. It implements the Brush interface and supports multiple color stops, proper sRGB color interpolation, and configurable extend modes.
RadialGradientBrush follows the vello/peniko gradient model, supporting both simple radial gradients (focus at center) and focal gradients (focus offset from center for spotlight effects).
Example:
// Simple radial gradient
gradient := gg.NewRadialGradientBrush(50, 50, 0, 50).
AddColorStop(0, gg.White).
AddColorStop(1, gg.Black)
// Focal gradient (spotlight effect)
spotlight := gg.NewRadialGradientBrush(50, 50, 0, 50).
SetFocus(30, 30).
AddColorStop(0, gg.White).
AddColorStop(1, gg.Black)
func NewRadialGradientBrush ¶ added in v0.12.0
func NewRadialGradientBrush(cx, cy, startRadius, endRadius float64) *RadialGradientBrush
NewRadialGradientBrush creates a new radial gradient. The gradient transitions from startRadius to endRadius around (cx, cy). Focus defaults to center.
func (*RadialGradientBrush) AddColorStop ¶ added in v0.12.0
func (g *RadialGradientBrush) AddColorStop(offset float64, c RGBA) *RadialGradientBrush
AddColorStop adds a color stop at the specified offset. Offset should be in the range [0, 1]. Returns the gradient for method chaining.
func (*RadialGradientBrush) ColorAt ¶ added in v0.12.0
func (g *RadialGradientBrush) ColorAt(x, y float64) RGBA
ColorAt returns the color at the given point. Implements the Pattern and Brush interfaces.
func (*RadialGradientBrush) SetExtend ¶ added in v0.12.0
func (g *RadialGradientBrush) SetExtend(mode ExtendMode) *RadialGradientBrush
SetExtend sets the extend mode for the gradient. Returns the gradient for method chaining.
func (*RadialGradientBrush) SetFocus ¶ added in v0.12.0
func (g *RadialGradientBrush) SetFocus(fx, fy float64) *RadialGradientBrush
SetFocus sets the focal point of the gradient. A focal point different from center creates an asymmetric gradient. Returns the gradient for method chaining.
type Rect ¶ added in v0.9.1
type Rect struct {
Min, Max Point
}
Rect represents an axis-aligned rectangle. Min is the top-left corner (minimum coordinates). Max is the bottom-right corner (maximum coordinates).
func NewRect ¶ added in v0.9.1
NewRect creates a rectangle from two points. The points are normalized so Min <= Max.
type Renderer ¶
type Renderer interface {
// Fill fills a path with the given paint.
Fill(pixmap *Pixmap, path *Path, paint *Paint)
// Stroke strokes a path with the given paint.
Stroke(pixmap *Pixmap, path *Path, paint *Paint)
}
Renderer is the interface for rendering paths to a pixmap.
type SoftwareRenderer ¶
type SoftwareRenderer struct {
// contains filtered or unexported fields
}
SoftwareRenderer is a CPU-based scanline rasterizer.
func NewSoftwareRenderer ¶
func NewSoftwareRenderer(width, height int) *SoftwareRenderer
NewSoftwareRenderer creates a new software renderer.
type SolidBrush ¶ added in v0.12.0
type SolidBrush struct {
// Color is the solid color of this brush.
Color RGBA
}
SolidBrush is a single-color brush. It implements the Brush interface and always returns the same color.
func Solid ¶ added in v0.12.0
func Solid(c RGBA) SolidBrush
Solid creates a SolidBrush from an RGBA color.
Example:
brush := gg.Solid(gg.Red)
brush := gg.Solid(gg.RGBA{R: 1, G: 0, B: 0, A: 1})
func SolidHex ¶ added in v0.12.0
func SolidHex(hex string) SolidBrush
SolidHex creates a SolidBrush from a hex color string. Supports formats: "RGB", "RGBA", "RRGGBB", "RRGGBBAA", with optional '#' prefix.
Example:
brush := gg.SolidHex("#FF5733")
brush := gg.SolidHex("FF5733")
brush := gg.SolidHex("#F53")
func SolidRGB ¶ added in v0.12.0
func SolidRGB(r, g, b float64) SolidBrush
SolidRGB creates a SolidBrush from RGB components (0-1 range). Alpha is set to 1.0 (fully opaque).
Example:
brush := gg.SolidRGB(1, 0, 0) // Red brush := gg.SolidRGB(0.5, 0.5, 0.5) // Gray
func SolidRGBA ¶ added in v0.12.0
func SolidRGBA(r, g, b, a float64) SolidBrush
SolidRGBA creates a SolidBrush from RGBA components (0-1 range).
Example:
brush := gg.SolidRGBA(1, 0, 0, 0.5) // Semi-transparent red
func (SolidBrush) ColorAt ¶ added in v0.12.0
func (b SolidBrush) ColorAt(_, _ float64) RGBA
ColorAt implements Brush. Returns the solid color regardless of position.
func (SolidBrush) Lerp ¶ added in v0.12.0
func (b SolidBrush) Lerp(other SolidBrush, t float64) SolidBrush
Lerp performs linear interpolation between two solid brushes. Returns a new SolidBrush with the interpolated color.
Example:
red := gg.Solid(gg.Red) blue := gg.Solid(gg.Blue) purple := red.Lerp(blue, 0.5)
func (SolidBrush) Opaque ¶ added in v0.12.0
func (b SolidBrush) Opaque() SolidBrush
Opaque returns a new SolidBrush with alpha set to 1.0.
func (SolidBrush) Transparent ¶ added in v0.12.0
func (b SolidBrush) Transparent() SolidBrush
Transparent returns a new SolidBrush with alpha set to 0.0.
func (SolidBrush) WithAlpha ¶ added in v0.12.0
func (b SolidBrush) WithAlpha(alpha float64) SolidBrush
WithAlpha returns a new SolidBrush with the specified alpha value. The RGB components are preserved.
Example:
opaqueBrush := gg.Solid(gg.Red) semiBrush := opaqueBrush.WithAlpha(0.5)
type SolidPattern ¶
type SolidPattern struct {
Color RGBA
}
SolidPattern represents a solid color pattern.
func NewSolidPattern ¶
func NewSolidPattern(color RGBA) *SolidPattern
NewSolidPattern creates a solid color pattern.
func (*SolidPattern) ColorAt ¶
func (p *SolidPattern) ColorAt(x, y float64) RGBA
ColorAt implements Pattern.
type Stroke ¶ added in v0.12.0
type Stroke struct {
// Width is the line width in pixels. Default: 1.0
Width float64
// Cap is the shape of line endpoints. Default: LineCapButt
Cap LineCap
// Join is the shape of line joins. Default: LineJoinMiter
Join LineJoin
// MiterLimit is the limit for miter joins before they become bevels.
// Default: 4.0 (common default, matches SVG)
MiterLimit float64
// Dash is the dash pattern for the stroke.
// nil means a solid line (no dashing).
Dash *Dash
}
Stroke defines the style for stroking paths. It encapsulates all stroke-related properties in a single struct, following the tiny-skia/kurbo pattern for unified stroke configuration.
func DashedStroke ¶ added in v0.12.0
DashedStroke returns a dashed stroke with the given pattern.
func DefaultStroke ¶ added in v0.12.0
func DefaultStroke() Stroke
DefaultStroke returns a Stroke with default settings. This creates a solid 1-pixel line with butt caps and miter joins.
func DottedStroke ¶ added in v0.12.0
func DottedStroke() Stroke
DottedStroke returns a dotted stroke. Uses round caps with equal dash and gap (1, 2 pattern with 2px width).
func RoundStroke ¶ added in v0.12.0
func RoundStroke() Stroke
RoundStroke returns a stroke with round caps and joins.
func SquareStroke ¶ added in v0.12.0
func SquareStroke() Stroke
SquareStroke returns a stroke with square caps.
func (Stroke) WithCap ¶ added in v0.12.0
WithCap returns a copy of the Stroke with the given line cap style.
func (Stroke) WithDash ¶ added in v0.12.0
WithDash returns a copy of the Stroke with the given dash pattern. Pass nil to remove dashing and return to solid lines.
func (Stroke) WithDashOffset ¶ added in v0.12.0
WithDashOffset returns a copy of the Stroke with the dash offset set. If there is no dash pattern, this has no effect.
func (Stroke) WithDashPattern ¶ added in v0.12.0
WithDashPattern returns a copy of the Stroke with a dash pattern created from the given lengths.
Example:
stroke.WithDashPattern(5, 3) // 5 units dash, 3 units gap
func (Stroke) WithJoin ¶ added in v0.12.0
WithJoin returns a copy of the Stroke with the given line join style.
func (Stroke) WithMiterLimit ¶ added in v0.12.0
WithMiterLimit returns a copy of the Stroke with the given miter limit. The miter limit controls when miter joins are converted to bevel joins. A value of 1.0 effectively disables miter joins.
type SweepGradientBrush ¶ added in v0.12.0
type SweepGradientBrush struct {
Center Point // Center of the sweep
StartAngle float64 // Start angle in radians
EndAngle float64 // End angle in radians (if 0, defaults to StartAngle + 2*Pi)
Stops []ColorStop // Color stops defining the gradient
Extend ExtendMode // How gradient extends beyond bounds
}
SweepGradientBrush represents an angular (conic) color transition around a center point. Colors sweep from StartAngle to EndAngle. Also known as a conic gradient. It implements the Brush interface and supports multiple color stops, proper sRGB color interpolation, and configurable extend modes.
SweepGradientBrush follows the vello/peniko gradient model, providing professional-quality angular gradients for effects like color wheels, pie charts, and radar displays.
Example:
// Color wheel
wheel := gg.NewSweepGradientBrush(50, 50, 0).
AddColorStop(0, gg.Red).
AddColorStop(0.166, gg.Yellow).
AddColorStop(0.333, gg.Green).
AddColorStop(0.5, gg.Cyan).
AddColorStop(0.666, gg.Blue).
AddColorStop(0.833, gg.Magenta).
AddColorStop(1, gg.Red)
func NewSweepGradientBrush ¶ added in v0.12.0
func NewSweepGradientBrush(cx, cy, startAngle float64) *SweepGradientBrush
NewSweepGradientBrush creates a new sweep (conic) gradient centered at (cx, cy). startAngle is the angle where the gradient begins (in radians). The gradient sweeps a full 360 degrees by default.
func (*SweepGradientBrush) AddColorStop ¶ added in v0.12.0
func (g *SweepGradientBrush) AddColorStop(offset float64, c RGBA) *SweepGradientBrush
AddColorStop adds a color stop at the specified offset. Offset should be in the range [0, 1]. Returns the gradient for method chaining.
func (*SweepGradientBrush) ColorAt ¶ added in v0.12.0
func (g *SweepGradientBrush) ColorAt(x, y float64) RGBA
ColorAt returns the color at the given point. Implements the Pattern and Brush interfaces.
func (*SweepGradientBrush) SetEndAngle ¶ added in v0.12.0
func (g *SweepGradientBrush) SetEndAngle(endAngle float64) *SweepGradientBrush
SetEndAngle sets the end angle of the sweep. Returns the gradient for method chaining.
func (*SweepGradientBrush) SetExtend ¶ added in v0.12.0
func (g *SweepGradientBrush) SetExtend(mode ExtendMode) *SweepGradientBrush
SetExtend sets the extend mode for the gradient. Returns the gradient for method chaining.
type Vec2 ¶ added in v0.9.1
type Vec2 struct {
X, Y float64
}
Vec2 represents a 2D displacement vector. Unlike Point which represents a position, Vec2 represents a direction and magnitude. This semantic distinction helps make code clearer when working with curve geometry.
func PointToVec2 ¶ added in v0.9.1
PointToVec2 converts Point to Vec2. Useful when you need to treat a position as a displacement.
func (Vec2) Approx ¶ added in v0.9.1
Approx returns true if two vectors are approximately equal within epsilon.
func (Vec2) Cross ¶ added in v0.9.1
Cross returns the 2D cross product (scalar). This is the z-component of the 3D cross product with z=0. Useful for determining the sign of the angle between vectors.
func (Vec2) LengthSq ¶ added in v0.9.1
LengthSq returns the squared length of the vector. This is faster than Length() when you only need to compare magnitudes.
func (Vec2) Lerp ¶ added in v0.9.1
Lerp performs linear interpolation between two vectors. t=0 returns v, t=1 returns w, intermediate values interpolate.
func (Vec2) Normalize ¶ added in v0.9.1
Normalize returns a unit vector in the same direction. Returns zero vector if the original vector has zero length.
func (Vec2) Perp ¶ added in v0.9.1
Perp returns the perpendicular vector (rotated 90 degrees counter-clockwise).
Source Files
¶
- brush.go
- brush_custom.go
- color.go
- context.go
- context_clip.go
- context_image.go
- context_layer.go
- context_mask.go
- curve.go
- dash.go
- doc.go
- gradient.go
- gradient_linear.go
- gradient_radial.go
- gradient_sweep.go
- mask.go
- matrix.go
- paint.go
- path.go
- path_builder.go
- path_ops.go
- pattern.go
- pixmap.go
- point.go
- renderer.go
- shapes.go
- software.go
- solver.go
- stroke.go
- text.go
- vec.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package backend provides a pluggable rendering backend abstraction.
|
Package backend provides a pluggable rendering backend abstraction. |
|
wgpu
Package wgpu provides a GPU-accelerated rendering backend using gogpu/wgpu.
|
Package wgpu provides a GPU-accelerated rendering backend using gogpu/wgpu. |
|
Package cache provides generic, high-performance caching primitives.
|
Package cache provides generic, high-performance caching primitives. |
|
cmd
|
|
|
ggdemo
command
Command ggdemo demonstrates the gg 2D graphics library.
|
Command ggdemo demonstrates the gg 2D graphics library. |
|
examples
|
|
|
basic
command
|
|
|
clipping
command
Package main demonstrates the clipping API in gogpu/gg.
|
Package main demonstrates the clipping API in gogpu/gg. |
|
gpu
command
Package main demonstrates the GPU backend for gogpu/gg.
|
Package main demonstrates the GPU backend for gogpu/gg. |
|
images
command
Package main demonstrates image drawing capabilities in gg.
|
Package main demonstrates image drawing capabilities in gg. |
|
scene
command
Package main demonstrates the scene graph (retained mode) API for gogpu/gg.
|
Package main demonstrates the scene graph (retained mode) API for gogpu/gg. |
|
shapes
command
|
|
|
text
command
|
|
|
text_fallback
command
|
|
|
internal
|
|
|
blend
Package blend implements advanced separable and non-separable blend modes.
|
Package blend implements advanced separable and non-separable blend modes. |
|
clip
Package clip provides geometric clipping for paths and shapes.
|
Package clip provides geometric clipping for paths and shapes. |
|
color
Package color provides color space types and conversions for gg.
|
Package color provides color space types and conversions for gg. |
|
filter
Package filter provides image filter implementations for the scene graph.
|
Package filter provides image filter implementations for the scene graph. |
|
image
Package image provides image buffer management for gogpu/gg.
|
Package image provides image buffer management for gogpu/gg. |
|
parallel
Package parallel provides tile-based parallel rendering infrastructure for gogpu/gg.
|
Package parallel provides tile-based parallel rendering infrastructure for gogpu/gg. |
|
path
Package path provides internal path processing utilities.
|
Package path provides internal path processing utilities. |
|
raster
Package raster provides scanline rasterization for 2D paths.
|
Package raster provides scanline rasterization for 2D paths. |
|
wide
Package wide provides SIMD-friendly wide types for batch pixel processing.
|
Package wide provides SIMD-friendly wide types for batch pixel processing. |
|
Package scene provides blend mode integration with internal/blend package.
|
Package scene provides blend mode integration with internal/blend package. |
|
Package text provides text rendering for gg.
|
Package text provides text rendering for gg. |
|
cache
Package cache provides high-performance caching for text shaping and rendering.
|
Package cache provides high-performance caching for text shaping and rendering. |
|
emoji
Package emoji provides emoji and color font support for text rendering.
|
Package emoji provides emoji and color font support for text rendering. |
|
msdf
Package msdf provides Multi-channel Signed Distance Field generation for high-quality, scalable text rendering on GPU.
|
Package msdf provides Multi-channel Signed Distance Field generation for high-quality, scalable text rendering on GPU. |