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 CloseAccelerator()
- func Logger() *slog.Logger
- func RegisterAccelerator(a GPUAccelerator) error
- func RegisterCoverageFiller(f CoverageFiller)
- func SDFCircleCoverage(px, py, cx, cy, radius, halfStrokeWidth float64) float64
- func SDFFilledCircleCoverage(px, py, cx, cy, radius float64) float64
- func SDFFilledRRectCoverage(px, py, cx, cy, halfW, halfH, cornerRadius float64) float64
- func SDFRRectCoverage(px, py, cx, cy, halfW, halfH, cornerRadius, halfStrokeWidth float64) float64
- func SetAcceleratorDeviceProvider(provider any) error
- func SetAcceleratorSurfaceTarget(view any, width, height uint32)
- func SetLogger(l *slog.Logger)
- 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 AcceleratedOp
- type Align
- type BlendMode
- type Brush
- func BrushFromPattern(p Pattern) Brushdeprecated
- type Close
- type ColorFunc
- type ColorStop
- type ComputePipelineAware
- 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) DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing float64, align Align)
- func (c *Context) EncodeJPEG(w io.Writer, quality int) error
- func (c *Context) EncodePNG(w io.Writer) error
- func (c *Context) Fill() error
- func (c *Context) FillBrush() Brush
- func (c *Context) FillPreserve() error
- func (c *Context) FlushGPU() error
- 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) GetTransform() Matrix
- 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) MeasureMultilineString(s string, lineSpacing float64) (width, height float64)
- func (c *Context) MeasureString(s string) (w, h float64)
- func (c *Context) MoveTo(x, y float64)
- func (c *Context) NewSubPath()
- func (c *Context) PipelineMode() PipelineMode
- 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) RasterizerMode() RasterizerMode
- func (c *Context) ResetClip()
- func (c *Context) Resize(width, height int) error
- func (c *Context) ResizeTarget() *Pixmap
- 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) SetPipelineMode(mode PipelineMode)
- 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) SetRasterizerMode(mode RasterizerMode)
- func (c *Context) SetStroke(stroke Stroke)
- func (c *Context) SetStrokeBrush(b Brush)
- func (c *Context) SetStrokePattern(pattern Pattern)
- func (c *Context) SetTransform(m Matrix)
- func (c *Context) Shear(x, y float64)
- func (c *Context) Stroke() error
- func (c *Context) StrokeBrush() Brush
- func (c *Context) StrokePreserve() error
- func (c *Context) Transform(m Matrix)
- func (c *Context) TransformPoint(x, y float64) (float64, float64)
- func (c *Context) Translate(x, y float64)
- func (c *Context) Width() int
- func (c *Context) WordWrap(s string, w float64) []string
- type ContextOption
- type CoverageFiller
- 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 DetectedShape
- type DeviceProviderAware
- type DrawImageOptions
- type ExtendMode
- type FillRule
- type ForceSDFAware
- type ForceableFiller
- type FuncPainter
- type GPUAccelerator
- type GPURenderTarget
- type GPUTextAccelerator
- 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
- func (m Matrix) Invert() Matrix
- func (m Matrix) IsIdentity() bool
- func (m Matrix) IsScaleOnly() bool
- func (m Matrix) IsTranslation() bool
- func (m Matrix) IsTranslationOnly() bool
- func (m Matrix) MaxScaleFactor() float64
- func (m Matrix) Multiply(other Matrix) Matrix
- func (m Matrix) ScaleFactor() float64
- func (m Matrix) TransformPoint(p Point) Point
- func (m Matrix) TransformVector(p Point) Point
- 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 Painter
- 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 PipelineMode
- type PipelineModeAware
- 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) SetPixelPremul(x, y int, r, g, b, a uint8)
- 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 RasterizerMode
- type Rect
- type Renderer
- type SDFAccelerator
- func (a *SDFAccelerator) CanAccelerate(op AcceleratedOp) bool
- func (a *SDFAccelerator) Close()
- func (a *SDFAccelerator) FillPath(_ GPURenderTarget, _ *Path, _ *Paint) error
- func (a *SDFAccelerator) FillShape(target GPURenderTarget, shape DetectedShape, paint *Paint) error
- func (a *SDFAccelerator) Flush(_ GPURenderTarget) error
- func (a *SDFAccelerator) Init() error
- func (a *SDFAccelerator) Name() string
- func (a *SDFAccelerator) SetForceSDF(force bool)
- func (a *SDFAccelerator) StrokePath(_ GPURenderTarget, _ *Path, _ *Paint) error
- func (a *SDFAccelerator) StrokeShape(target GPURenderTarget, shape DetectedShape, paint *Paint) error
- type SceneStats
- type SceneStatsTracker
- type ShapeKind
- type SoftwareRenderer
- type SolidBrush
- type SolidPainter
- 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 SurfaceTargetAware
- 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.
const ( AlignLeft = text.AlignLeft AlignCenter = text.AlignCenter AlignRight = text.AlignRight )
Alignment constants re-exported from the text package for convenience.
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
var ErrFallbackToCPU = errors.New("gg: falling back to CPU rendering")
ErrFallbackToCPU indicates the GPU accelerator cannot handle this operation. The caller should transparently fall back to CPU rendering.
Functions ¶
func CloseAccelerator ¶ added in v0.28.0
func CloseAccelerator()
CloseAccelerator shuts down the global GPU accelerator, releasing all GPU resources (textures, pipelines, device, instance). After this call, Accelerator returns nil and rendering falls back to CPU.
Call this at application shutdown to prevent VkImage and other GPU memory leaks. It is safe to call when no accelerator is registered (no-op). CloseAccelerator is idempotent.
Example:
defer gg.CloseAccelerator()
func Logger ¶ added in v0.28.0
Logger returns the current logger used by gg. Sub-packages (gpu/, integration/ggcanvas/) call this to share the same logger configuration without introducing import cycles.
Logger is safe for concurrent use.
func RegisterAccelerator ¶ added in v0.25.1
func RegisterAccelerator(a GPUAccelerator) error
RegisterAccelerator registers a GPU accelerator for optional GPU rendering.
Only one accelerator can be registered. Subsequent calls replace the previous one. The accelerator's Init() method is called during registration. If Init() fails, the accelerator is not registered and the error is returned.
Typical usage via blank import in GPU backend packages:
func init() {
gg.RegisterAccelerator(NewWGPUAccelerator())
}
func RegisterCoverageFiller ¶ added in v0.32.0
func RegisterCoverageFiller(f CoverageFiller)
RegisterCoverageFiller registers a tile-based coverage filler for complex paths.
Only one filler can be registered. Subsequent calls replace the previous one. Typical usage via blank import in the gpu package:
func init() {
gg.RegisterCoverageFiller(&gpuimpl.SparseStripsFiller{})
}
func SDFCircleCoverage ¶ added in v0.27.0
SDFCircleCoverage computes anti-aliased coverage for a stroked circle using a signed distance field approach.
Parameters:
- px, py: pixel center coordinates
- cx, cy: circle center
- radius: circle radius (to center of stroke)
- halfStrokeWidth: half the stroke width
Returns a coverage value in [0, 1] where 1 means fully inside the stroke.
func SDFFilledCircleCoverage ¶ added in v0.27.0
SDFFilledCircleCoverage computes anti-aliased coverage for a filled circle using a signed distance field approach.
Parameters:
- px, py: pixel center coordinates
- cx, cy: circle center
- radius: circle radius
Returns a coverage value in [0, 1] where 1 means fully inside.
func SDFFilledRRectCoverage ¶ added in v0.27.0
SDFFilledRRectCoverage computes anti-aliased coverage for a filled rounded rectangle using a signed distance field approach.
Parameters:
- px, py: pixel center coordinates
- cx, cy: rectangle center
- halfW, halfH: half-width and half-height of the rectangle
- cornerRadius: radius of the rounded corners
Returns a coverage value in [0, 1] where 1 means fully inside.
func SDFRRectCoverage ¶ added in v0.27.0
SDFRRectCoverage computes anti-aliased coverage for a stroked rounded rectangle using a signed distance field approach.
Parameters:
- px, py: pixel center coordinates
- cx, cy: rectangle center
- halfW, halfH: half-width and half-height of the rectangle
- cornerRadius: radius of the rounded corners
- halfStrokeWidth: half the stroke width
Returns a coverage value in [0, 1] where 1 means fully inside the stroke.
func SetAcceleratorDeviceProvider ¶ added in v0.27.0
SetAcceleratorDeviceProvider passes a device provider to the registered accelerator, enabling GPU device sharing. If no accelerator is registered or it doesn't support device sharing, this is a no-op.
The provider should implement HalDevice() any and HalQueue() any methods that return wgpu/hal types.
func SetAcceleratorSurfaceTarget ¶ added in v0.28.0
SetAcceleratorSurfaceTarget configures the registered accelerator for direct surface rendering. When view is non-nil, the accelerator renders directly to the surface texture view, eliminating GPU->CPU readback. Call with nil view to return to offscreen mode.
If no accelerator is registered or it doesn't support surface rendering, this is a no-op. The view parameter should be a hal.TextureView.
func SetLogger ¶ added in v0.28.0
SetLogger configures the logger for gg and all its sub-packages. By default, gg produces no log output. Call SetLogger to enable logging.
SetLogger is safe for concurrent use: it stores the new logger atomically. Pass nil to disable logging (restore default silent behavior).
Log levels used by gg:
- slog.LevelDebug: internal diagnostics (GPU pipeline state, buffer sizes)
- slog.LevelInfo: important lifecycle events (GPU adapter selected)
- slog.LevelWarn: non-fatal issues (CPU fallback, resource release errors)
Example:
// Enable info-level logging to stderr:
gg.SetLogger(slog.Default())
// Enable debug-level logging for full diagnostics:
gg.SetLogger(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelDebug,
})))
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 AcceleratedOp ¶ added in v0.25.1
type AcceleratedOp uint32
AcceleratedOp describes operation types for GPU capability checking.
const ( // AccelFill represents path fill operations. AccelFill AcceleratedOp = 1 << iota // AccelStroke represents path stroke operations. AccelStroke // AccelScene represents full scene rendering. AccelScene // AccelText represents text rendering. AccelText // AccelImage represents image compositing. AccelImage // AccelGradient represents gradient rendering. AccelGradient // AccelCircleSDF represents SDF-based circle rendering. AccelCircleSDF // AccelRRectSDF represents SDF-based rounded rectangle rendering. AccelRRectSDF )
type Align ¶ added in v0.31.0
Align specifies text horizontal alignment. This is a type alias for text.Alignment, provided for fogleman/gg compatibility.
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 ComputePipelineAware ¶ added in v0.30.0
type ComputePipelineAware interface {
// CanCompute reports whether the compute pipeline is available and ready.
CanCompute() bool
}
ComputePipelineAware is an optional interface for accelerators that support the Vello-style compute pipeline. When the accelerator implements this interface and PipelineMode is Auto or Compute, the framework uses the compute pipeline for complex scenes instead of the render pass pipeline.
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 ¶
func NewContext(width, height int, opts ...ContextOption) *Context
NewContext creates a new drawing context with the given dimensions. Optional ContextOption arguments can be used for dependency injection:
// Default software rendering (uses analytic anti-aliasing) dc := gg.NewContext(800, 600) // Custom GPU renderer (dependency injection) dc := gg.NewContext(800, 600, gg.WithRenderer(gpuRenderer))
func NewContextForImage ¶
func NewContextForImage(img image.Image, opts ...ContextOption) *Context
NewContextForImage creates a context for drawing on an existing image. Optional ContextOption arguments can be used for dependency injection.
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.
Close flushes any pending GPU accelerator operations to ensure all queued draw commands are rendered before releasing context state. Note: Close does NOT shut down the global GPU accelerator itself, since it may be shared by other contexts. To release GPU resources at application shutdown, call CloseAccelerator.
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.
If a GPU accelerator is registered and supports text rendering (implements GPUTextAccelerator), the text is rendered via the GPU MSDF pipeline. The CTM (Current Transform Matrix) is passed to the GPU so that Scale, Rotate, and Skew transforms affect text rendering, not just position. Otherwise, the CPU text pipeline is used with transform-aware rendering:
- Translation-only: bitmap fast path (zero quality loss)
- Uniform scale ≤256px: bitmap at device size (Strategy A, Skia pattern)
- Everything else: glyph outlines as vector paths (Strategy B, Vello pattern)
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) DrawStringWrapped ¶ added in v0.31.0
func (c *Context) DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing float64, align Align)
DrawStringWrapped wraps text to the given width and draws it with alignment. The text is positioned relative to (x, y) using the anchor (ax, ay):
(0, 0) = top-left of the text block is at (x, y) (0.5, 0.5) = center of the text block is at (x, y) (1, 1) = bottom-right of the text block is at (x, y)
The lineSpacing parameter multiplies the font's natural line height (1.0 = normal, 1.5 = 50% extra space between lines). The align parameter controls horizontal alignment within the wrapped width. If no font face is set, this method does nothing.
This method is compatible with fogleman/gg's DrawStringWrapped.
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) Fill ¶
Fill fills the current path and clears it. If a GPU accelerator is registered and supports the path, it is used first. Otherwise, the software renderer handles the operation. The RasterizerMode set via SetRasterizerMode controls algorithm selection. Returns an error if the rendering operation fails.
func (*Context) FillPreserve ¶
FillPreserve fills the current path without clearing it. If a GPU accelerator is registered and supports the path, it is used first. Otherwise, the software renderer handles the operation. Returns an error if the rendering operation fails.
func (*Context) FlushGPU ¶ added in v0.27.0
FlushGPU flushes any pending GPU accelerator operations to the pixel buffer. Call this before reading pixel data (e.g., SavePNG, Image) when using a batch-capable GPU accelerator. For immediate-mode accelerators this is a no-op.
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) GetTransform ¶ added in v0.21.0
GetTransform returns a copy of the current transformation matrix. This is similar to CanvasRenderingContext2D.getTransform() in web browsers. The returned matrix is a copy, so modifying it will not affect the context.
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) MeasureMultilineString ¶ added in v0.31.0
MeasureMultilineString measures text that may contain newlines. The lineSpacing parameter is a multiplier for the font's natural line height (1.0 = normal spacing, 1.5 = 50% extra space between lines). Returns (width, height) where width is the maximum line width and height is the total height of all lines with the given line spacing. If no font face is set, returns (0, 0).
This method is compatible with fogleman/gg's MeasureMultilineString.
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) PipelineMode ¶ added in v0.30.0
func (c *Context) PipelineMode() PipelineMode
PipelineMode returns the current pipeline mode.
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) RasterizerMode ¶ added in v0.32.0
func (c *Context) RasterizerMode() RasterizerMode
RasterizerMode returns the current rasterizer mode.
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) Resize ¶ added in v0.21.0
Resize changes the context dimensions, reusing internal buffers where possible. If the dimensions haven't changed, this is a no-op. Returns an error if width or height is <= 0.
After Resize:
- The pixmap is reallocated only if dimensions changed
- The clip region is reset to the full rectangle
- The transformation matrix is preserved (Push/Pop stack is preserved)
- The current path is cleared
This method is useful for UI frameworks that need to resize the canvas when the window size changes, without creating a new Context.
func (*Context) ResizeTarget ¶ added in v0.21.0
ResizeTarget returns the underlying pixmap for resize operations. This is primarily used by renderers and advanced users who need direct access to the target buffer during resize operations.
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. It also updates the Brush field for consistency with ColorAt precedence.
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) SetPipelineMode ¶ added in v0.30.0
func (c *Context) SetPipelineMode(mode PipelineMode)
SetPipelineMode sets the GPU rendering pipeline mode. See PipelineMode for available modes.
If the registered accelerator implements PipelineModeAware, the mode is propagated so the accelerator can route operations to the correct pipeline (render pass vs compute).
func (*Context) SetRasterizerMode ¶ added in v0.32.0
func (c *Context) SetRasterizerMode(mode RasterizerMode)
SetRasterizerMode sets the rasterization strategy for this context. RasterizerAuto (default) uses intelligent auto-selection based on path complexity, bounding box area, and shape type. Other modes force a specific algorithm, bypassing auto-selection.
The mode is per-Context — different contexts can use different strategies.
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. It also updates the Brush field for consistency with ColorAt precedence.
func (*Context) SetTransform ¶ added in v0.21.0
SetTransform replaces the current transformation matrix with the given matrix. This is similar to CanvasRenderingContext2D.setTransform() in web browsers. Unlike Transform, this completely replaces the matrix rather than multiplying.
func (*Context) Stroke ¶
Stroke strokes the current path and clears it. If a GPU accelerator is registered and supports the path, it is used first. Otherwise, the software renderer handles the operation. The RasterizerMode set via SetRasterizerMode controls algorithm selection. Returns an error if the rendering operation fails.
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 ¶
StrokePreserve strokes the current path without clearing it. If a GPU accelerator is registered and supports the path, it is used first. Otherwise, the software renderer handles the operation. Returns an error if the rendering operation fails.
func (*Context) Transform ¶ added in v0.21.0
Transform multiplies the current transformation matrix by the given matrix. This is similar to CanvasRenderingContext2D.transform() in web browsers. The transformation is applied in the order: current * m.
func (*Context) TransformPoint ¶
TransformPoint transforms a point by the current matrix.
type ContextOption ¶ added in v0.18.0
type ContextOption func(*contextOptions)
ContextOption configures a Context during creation. Use functional options to customize Context behavior.
Example:
// Default software rendering dc := gg.NewContext(800, 600) // Custom GPU renderer (dependency injection) dc := gg.NewContext(800, 600, gg.WithRenderer(gpuRenderer))
func WithPipelineMode ¶ added in v0.30.0
func WithPipelineMode(mode PipelineMode) ContextOption
WithPipelineMode sets the GPU pipeline mode for the Context. Default is PipelineModeAuto, which lets the framework choose.
Example:
// Force compute pipeline dc := gg.NewContext(800, 600, gg.WithPipelineMode(gg.PipelineModeCompute))
func WithPixmap ¶ added in v0.18.0
func WithPixmap(pm *Pixmap) ContextOption
WithPixmap sets a custom pixmap for the Context. The pixmap dimensions should match the Context dimensions.
Example:
pm := gg.NewPixmap(800, 600) dc := gg.NewContext(800, 600, gg.WithPixmap(pm))
func WithRenderer ¶ added in v0.18.0
func WithRenderer(r Renderer) ContextOption
WithRenderer sets a custom renderer for the Context. Use this for dependency injection of GPU or custom renderers.
Example:
// Using a custom renderer customRenderer := mypackage.NewRenderer() dc := gg.NewContext(800, 600, gg.WithRenderer(customRenderer))
For GPU-accelerated rendering, see gg's gpu backend (internal/gpu/) which uses gogpu/wgpu directly.
type CoverageFiller ¶ added in v0.32.0
type CoverageFiller interface {
// FillCoverage rasterizes the path and calls callback for each pixel
// with non-zero coverage. The coverage value is 0-255 (anti-aliased alpha).
FillCoverage(path *Path, width, height int, fillRule FillRule,
callback func(x, y int, coverage uint8))
}
CoverageFiller is a tile-based coverage rasterizer for complex paths.
When registered via RegisterCoverageFiller, the SoftwareRenderer auto-selects it for paths above a complexity threshold (coverageFillerThreshold elements). For simpler paths, the AnalyticFiller (scanline) is used directly.
The callback receives per-pixel coverage values (0-255) that the caller composites onto the target pixmap using source-over blending.
Implementations:
- SparseStripsFiller (4x4 tiles, CPU/SIMD-optimized) — default
- TileComputeFiller (16x16 tiles, GPU workgroup-ready) — alternative
func GetCoverageFiller ¶ added in v0.32.0
func GetCoverageFiller() CoverageFiller
GetCoverageFiller returns the registered CoverageFiller, or nil if none.
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) Scale ¶ added in v0.21.2
Scale returns a new Dash with all lengths multiplied by the given factor. This is used to scale dash patterns when a transform is applied to the path. Per Cairo/Skia convention, dash lengths are in user-space units, so they must be scaled along with the coordinate transform.
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 DetectedShape ¶ added in v0.27.0
type DetectedShape struct {
Kind ShapeKind
CenterX float64 // Center X coordinate.
CenterY float64 // Center Y coordinate.
RadiusX float64 // X radius. For circle: RadiusX == RadiusY.
RadiusY float64 // Y radius. For circle: RadiusX == RadiusY.
Width float64 // Total width for rect/rrect.
Height float64 // Total height for rect/rrect.
CornerRadius float64 // Corner radius for rrect only.
}
DetectedShape holds parameters of a recognized geometric shape. The Kind field indicates which parameters are meaningful.
func DetectShape ¶ added in v0.27.0
func DetectShape(path *Path) DetectedShape
DetectShape analyzes a Path and returns the identified shape if recognized. Returns a DetectedShape with Kind == ShapeUnknown if the path cannot be identified as a simple geometric primitive.
type DeviceProviderAware ¶ added in v0.27.0
DeviceProviderAware is an optional interface for accelerators that can share GPU resources with an external provider (e.g., gogpu window). When SetDeviceProvider is called, the accelerator reuses the provided GPU device instead of creating its own.
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 ForceSDFAware ¶ added in v0.32.0
type ForceSDFAware interface {
SetForceSDF(force bool)
}
ForceSDFAware is an optional interface for GPU accelerators that support forced SDF rendering. When enabled, the accelerator bypasses the minimum size check for SDF shapes, allowing RasterizerSDF mode to force SDF rendering regardless of shape size.
type ForceableFiller ¶ added in v0.32.0
type ForceableFiller interface {
CoverageFiller
// SparseFiller returns the SparseStrips (4x4 tiles) filler component.
SparseFiller() CoverageFiller
// ComputeFiller returns the TileCompute (16x16 tiles) filler component.
ComputeFiller() CoverageFiller
}
ForceableFiller is an optional interface for CoverageFillers that support forced algorithm selection. When the user sets RasterizerSparseStrips or RasterizerTileCompute mode, the renderer uses SparseFiller() or ComputeFiller() instead of the adaptive auto-selection.
type FuncPainter ¶ added in v0.24.0
FuncPainter wraps a ColorAt function as a Painter (per-pixel sampling).
func (*FuncPainter) PaintSpan ¶ added in v0.24.0
func (p *FuncPainter) PaintSpan(dest []RGBA, x, y, length int)
PaintSpan samples the color function at each pixel center.
type GPUAccelerator ¶ added in v0.25.1
type GPUAccelerator interface {
// Name returns the accelerator name (e.g., "wgpu", "vulkan").
Name() string
// Init initializes GPU resources. Called once during registration.
Init() error
// Close releases GPU resources.
Close()
// CanAccelerate reports whether the accelerator supports the given operation.
// This is a fast check used to skip GPU entirely for unsupported operations.
CanAccelerate(op AcceleratedOp) bool
// FillPath renders a filled path to the target.
// Returns ErrFallbackToCPU if the path cannot be GPU-accelerated.
FillPath(target GPURenderTarget, path *Path, paint *Paint) error
// StrokePath renders a stroked path to the target.
// Returns ErrFallbackToCPU if the path cannot be GPU-accelerated.
StrokePath(target GPURenderTarget, path *Path, paint *Paint) error
// FillShape renders a detected shape using SDF.
// This is the fast path for circles and rounded rectangles.
// Returns ErrFallbackToCPU if the shape is not supported.
FillShape(target GPURenderTarget, shape DetectedShape, paint *Paint) error
// StrokeShape renders a detected shape outline using SDF.
// Returns ErrFallbackToCPU if the shape is not supported.
StrokeShape(target GPURenderTarget, shape DetectedShape, paint *Paint) error
// Flush dispatches any pending GPU operations to the target pixel buffer.
// Batch-capable accelerators accumulate shapes during FillShape/StrokeShape
// and dispatch them all in a single GPU pass on Flush.
// Immediate-mode accelerators (e.g., CPU SDF) return nil.
Flush(target GPURenderTarget) error
}
GPUAccelerator is an optional GPU acceleration provider.
When registered via RegisterAccelerator, the Context tries GPU acceleration first for supported operations. If the accelerator returns ErrFallbackToCPU or any error, rendering transparently falls back to CPU.
Implementations should be provided by GPU backend packages (e.g., gg/gpu/). Users opt in to GPU acceleration via blank import:
import _ "github.com/gogpu/gg/gpu" // enables GPU acceleration
func Accelerator ¶ added in v0.25.1
func Accelerator() GPUAccelerator
Accelerator returns the currently registered GPU accelerator, or nil if none.
type GPURenderTarget ¶ added in v0.27.0
GPURenderTarget provides pixel buffer access for GPU output. The Data slice must be in premultiplied RGBA format, 4 bytes per pixel, laid out row by row with the given Stride.
type GPUTextAccelerator ¶ added in v0.29.0
type GPUTextAccelerator interface {
// DrawText renders text at position (x, y) in user space where y is the
// baseline. The face provides font metrics and glyph iteration. Color is
// the text color in RGBA. The matrix parameter is the context's current
// transformation matrix (CTM), which the GPU pipeline composes into the
// vertex shader uniform so that Scale, Rotate, and Skew transforms
// affect text rendering, not just position.
// Returns ErrFallbackToCPU if GPU text rendering is not available.
DrawText(target GPURenderTarget, face any, text string, x, y float64, color RGBA, matrix Matrix) error
}
GPUTextAccelerator is an optional interface for accelerators that support GPU-accelerated text rendering via MSDF (Multi-channel Signed Distance Field). When the registered accelerator implements this interface, Context.DrawString will use the GPU pipeline instead of CPU freetype.
Text is rendered as Tier 4 in the unified render pass, after SDF shapes, convex polygons, and stencil-then-cover paths. The MSDF approach provides resolution-independent, crisp text at any scale.
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, WebP.
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) IsScaleOnly ¶ added in v0.32.1
IsScaleOnly reports whether the matrix has only scale (and possibly translation), with no rotation or skew. The off-diagonal elements of the 2x2 linear portion must be zero.
Note that this returns true for identity and pure translation matrices as well, since those are special cases of scale (with scale factors of 1).
func (Matrix) IsTranslation ¶
IsTranslation returns true if the matrix is only a translation.
func (Matrix) IsTranslationOnly ¶ added in v0.32.1
IsTranslationOnly reports whether the matrix is identity or pure translation (no scale, rotation, or skew). The 2x2 linear portion must be the identity.
This is equivalent to IsTranslation but named for clarity in the text rendering pipeline where the distinction between "translation only" and "scale only" determines the rasterization algorithm.
func (Matrix) MaxScaleFactor ¶ added in v0.32.1
MaxScaleFactor returns the maximum axis scale factor of the transformation. This is the largest singular value of the 2x2 linear portion of the matrix, representing the maximum stretch in any direction.
For a pure scale matrix Scale(sx, sy), returns max(|sx|, |sy|). For a rotation matrix, returns 1.0 (rotation preserves lengths). For general matrices (with rotation and/or skew), computes the spectral norm via the eigenvalues of M^T * M.
This matches the approach used by Skia (SkMatrix::getMaxScale) and Cairo (_cairo_matrix_compute_basis_scale_factors).
Returns 0 if the matrix is degenerate (zero area).
func (Matrix) ScaleFactor ¶ added in v0.21.2
ScaleFactor returns the maximum scale factor of the transformation. This is useful for determining effective stroke width after transform. For a pure scale matrix Scale(sx, sy), returns max(sx, sy). For rotation/shear, returns the maximum singular value.
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
// TransformScale is the scale factor from the current transform matrix.
// Used internally by the renderer to determine effective stroke width.
// Set automatically by Context.Stroke() before rendering.
TransformScale float64
}
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 Painter ¶ added in v0.24.0
type Painter interface {
// PaintSpan fills dest with colors for pixels starting at (x, y) for length pixels.
PaintSpan(dest []RGBA, x, y, length int)
}
Painter generates colors for rendering operations. For simple use cases, implement Pattern instead — it auto-wraps via PainterFromPaint. For maximum performance, implement Painter directly with span-based color generation.
func PainterFromPaint ¶ added in v0.24.0
PainterFromPaint creates the appropriate Painter for a Paint. Solid paints return SolidPainter (fast). Non-solid paints return FuncPainter that samples paint.ColorAt per pixel.
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 PipelineMode ¶ added in v0.30.0
type PipelineMode int
PipelineMode selects the GPU rendering pipeline.
const ( // PipelineModeAuto lets the framework select the best pipeline // based on scene complexity and GPU capabilities. PipelineModeAuto PipelineMode = iota // PipelineModeRenderPass forces the traditional multi-tier render pass // pipeline (SDF, Convex, Stencil-then-Cover, MSDF Text). PipelineModeRenderPass // PipelineModeCompute forces the Vello-style compute pipeline // (scene encoding, tile binning, PTCL fine rasterization). PipelineModeCompute )
func SelectPipeline ¶ added in v0.31.0
func SelectPipeline(stats SceneStats, hasComputeSupport bool) PipelineMode
SelectPipeline chooses the best pipeline based on scene statistics and GPU capabilities.
Heuristics:
- Simple scenes (< 10 shapes, shallow clips): RenderPass is faster (no encoding overhead, direct GPU draw calls)
- Complex scenes (> 50 shapes, deep clips, high overlap): Compute excels (massively parallel tile-based processing)
- Text-heavy: RenderPass (MSDF Text tier is specialized)
- Default for medium complexity: Compute
func (PipelineMode) String ¶ added in v0.30.0
func (m PipelineMode) String() string
String returns the pipeline mode name.
type PipelineModeAware ¶ added in v0.31.0
type PipelineModeAware interface {
// SetPipelineMode sets the pipeline mode for subsequent operations.
SetPipelineMode(mode PipelineMode)
}
PipelineModeAware is an optional interface for accelerators that support pipeline mode selection (render pass vs compute). When the registered accelerator implements this interface, the Context propagates pipeline mode changes so the accelerator can route operations accordingly.
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) At ¶
At implements the image.Image interface. Returns premultiplied color.RGBA directly from the internal buffer.
func (*Pixmap) Clear ¶
Clear fills the entire pixmap with a color. The color is stored in premultiplied alpha format.
func (*Pixmap) ColorModel ¶
ColorModel implements the image.Image interface. Returns RGBAModel because the pixmap stores premultiplied alpha data.
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) GetPixel ¶
GetPixel returns the color of a single pixel as straight (non-premultiplied) RGBA. Internally the pixel is stored as premultiplied alpha; this method un-premultiplies.
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.
func (*Pixmap) SetPixel ¶
SetPixel sets the color of a single pixel. The color is stored in premultiplied alpha format internally.
func (*Pixmap) SetPixelPremul ¶ added in v0.31.0
SetPixelPremul sets a pixel using premultiplied RGBA uint8 values directly. This skips the float-to-uint8 conversion, clamping, and premultiplication overhead of SetPixel. Use this when colors are precomputed for batch operations.
Values must already be in premultiplied alpha form and clamped to [0, 255]. Out-of-bounds coordinates are silently ignored.
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 FromColor ¶
FromColor converts a standard color.Color to straight-alpha RGBA. Go's color.Color.RGBA() returns premultiplied values; this un-premultiplies them.
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) RGBA ¶ added in v0.31.0
RGBA implements the color.Color interface. Returns premultiplied alpha values scaled to [0, 65535] as required by the interface. This allows gg.RGBA to be used directly with dc.SetColor(gg.Black).
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 RasterizerMode ¶ added in v0.32.0
type RasterizerMode int
RasterizerMode controls which rasterization algorithm is used for path rendering.
The default is RasterizerAuto, which uses intelligent multi-factor auto-selection based on path complexity, bounding box area, and shape type. Force modes bypass auto-selection and always use a specific algorithm.
The mode is per-Context, not global. Different contexts can use different strategies.
Use cases for force modes:
- Debugging: force AnalyticFiller to isolate tile rasterizer bugs
- Benchmarking: compare algorithms on the same workload
- Known workload: user knows their data better than heuristics
- Quality control: force SDF for maximum circle/rrect quality
- Regression testing: ensure each algorithm produces correct output
const ( // RasterizerAuto uses intelligent multi-factor auto-selection (default). // It considers path complexity, bounding box area, shape type, and registered // fillers to choose the optimal algorithm per-path. RasterizerAuto RasterizerMode = iota // RasterizerAnalytic forces the AnalyticFiller (scanline) for all paths. // This bypasses CoverageFiller entirely, even for complex paths. // Best for: debugging, simple UIs, guaranteed minimal overhead. RasterizerAnalytic // RasterizerSparseStrips forces SparseStrips (4x4 tiles) for all paths. // Bypasses the adaptive threshold and always uses SparseStrips regardless // of path complexity. // Requires a CoverageFiller with ForceableFiller support to be registered. // Best for: CPU-optimized rendering, SIMD-friendly workloads. RasterizerSparseStrips // RasterizerTileCompute forces TileCompute (16x16 tiles) for all paths. // Bypasses the adaptive threshold and always uses TileCompute regardless // of path complexity. // Requires a CoverageFiller with ForceableFiller support to be registered. // Best for: GPU workgroup-ready workloads, extreme complexity. RasterizerTileCompute // RasterizerSDF forces SDF rendering for detected shapes, bypassing the // minimum size check. Non-SDF shapes fall back to auto-selection. // Best for: maximum visual quality on geometric shapes (circles, rrects). RasterizerSDF )
func (RasterizerMode) String ¶ added in v0.32.0
func (m RasterizerMode) String() string
String returns the rasterizer mode name.
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.
// Returns an error if the rendering operation fails.
Fill(pixmap *Pixmap, path *Path, paint *Paint) error
// Stroke strokes a path with the given paint.
// Returns an error if the rendering operation fails.
Stroke(pixmap *Pixmap, path *Path, paint *Paint) error
}
Renderer is the interface for rendering paths to a pixmap.
type SDFAccelerator ¶ added in v0.27.0
type SDFAccelerator struct {
// contains filtered or unexported fields
}
SDFAccelerator is a CPU-based SDF accelerator for simple geometric shapes. It produces smoother circles and rounded rectangles than the default area-based rasterizer by computing per-pixel signed distance fields.
This accelerator only handles circles and rounded rectangles via the AccelCircleSDF and AccelRRectSDF operations. All other operations fall back to the software renderer.
Shapes smaller than sdfMinSize pixels in either dimension are rejected (ErrFallbackToCPU) so AnalyticFiller handles them with lower overhead.
Usage:
gg.RegisterAccelerator(&gg.SDFAccelerator{})
func (*SDFAccelerator) CanAccelerate ¶ added in v0.27.0
func (a *SDFAccelerator) CanAccelerate(op AcceleratedOp) bool
CanAccelerate reports whether the accelerator supports the given operation. Only circle and rounded-rect SDF operations are supported.
func (*SDFAccelerator) Close ¶ added in v0.27.0
func (a *SDFAccelerator) Close()
Close releases resources. No-op for CPU-based SDF.
func (*SDFAccelerator) FillPath ¶ added in v0.27.0
func (a *SDFAccelerator) FillPath(_ GPURenderTarget, _ *Path, _ *Paint) error
FillPath always falls back to CPU for general paths.
func (*SDFAccelerator) FillShape ¶ added in v0.27.0
func (a *SDFAccelerator) FillShape(target GPURenderTarget, shape DetectedShape, paint *Paint) error
FillShape renders a filled shape using SDF. Shapes smaller than sdfMinSize in either dimension fall back to CPU scanline, unless forceSDF is enabled (RasterizerSDF mode).
func (*SDFAccelerator) Flush ¶ added in v0.27.0
func (a *SDFAccelerator) Flush(_ GPURenderTarget) error
Flush is a no-op for the CPU SDF accelerator (renders immediately).
func (*SDFAccelerator) Init ¶ added in v0.27.0
func (a *SDFAccelerator) Init() error
Init initializes the accelerator. No resources are needed.
func (*SDFAccelerator) Name ¶ added in v0.27.0
func (a *SDFAccelerator) Name() string
Name returns the accelerator name.
func (*SDFAccelerator) SetForceSDF ¶ added in v0.32.0
func (a *SDFAccelerator) SetForceSDF(force bool)
SetForceSDF enables or disables forced SDF mode. When enabled, FillShape/StrokeShape skip the minimum size check, allowing SDF rendering for shapes smaller than sdfMinSize.
func (*SDFAccelerator) StrokePath ¶ added in v0.27.0
func (a *SDFAccelerator) StrokePath(_ GPURenderTarget, _ *Path, _ *Paint) error
StrokePath always falls back to CPU for general paths.
func (*SDFAccelerator) StrokeShape ¶ added in v0.27.0
func (a *SDFAccelerator) StrokeShape(target GPURenderTarget, shape DetectedShape, paint *Paint) error
StrokeShape renders a stroked shape using SDF. Shapes smaller than sdfMinSize in either dimension fall back to CPU scanline, unless forceSDF is enabled (RasterizerSDF mode).
type SceneStats ¶ added in v0.30.0
type SceneStats struct {
ShapeCount int // Total number of shapes
PathCount int // Complex paths (not simple SDF shapes)
TextCount int // Text elements
ClipDepth int // Maximum clip nesting depth
OverlapFactor float64 // Estimated overlap ratio [0, 1]
}
SceneStats holds metrics for pipeline auto-selection. These are computed by analyzing the current frame's draw operations.
type SceneStatsTracker ¶ added in v0.31.0
type SceneStatsTracker interface {
// SceneStats returns the accumulated scene statistics for the current frame.
SceneStats() SceneStats
}
SceneStatsTracker is an optional interface for accelerators that track per-frame scene statistics for auto pipeline selection. The Context does not call these methods directly — the accelerator uses them internally.
type ShapeKind ¶ added in v0.27.0
type ShapeKind int
ShapeKind identifies detected shapes for GPU SDF acceleration.
const ( // ShapeUnknown indicates the path is too complex for shape detection. ShapeUnknown ShapeKind = iota // ShapeCircle indicates a circular path. ShapeCircle // ShapeEllipse indicates an elliptical path. ShapeEllipse // ShapeRect indicates an axis-aligned rectangular path. ShapeRect // ShapeRRect indicates a rounded rectangle path. ShapeRRect )
type SoftwareRenderer ¶
type SoftwareRenderer struct {
// contains filtered or unexported fields
}
SoftwareRenderer is a CPU-based scanline rasterizer using analytic anti-aliasing.
Analytic AA computes the exact area of the shape within each pixel using trapezoidal integration. This provides higher quality anti-aliasing than supersampling approaches, with no extra memory overhead.
func NewSoftwareRenderer ¶
func NewSoftwareRenderer(width, height int) *SoftwareRenderer
NewSoftwareRenderer creates a new software renderer with analytic anti-aliasing.
func (*SoftwareRenderer) Fill ¶
func (r *SoftwareRenderer) Fill(pixmap *Pixmap, p *Path, paint *Paint) error
Fill implements Renderer.Fill using analytic anti-aliasing. For complex paths, it auto-selects the registered CoverageFiller (tile-based rasterizer) when available, using an adaptive threshold based on both path element count and bounding box area.
When rasterizerMode is set (via Context.SetRasterizerMode), the forced algorithm is used instead of auto-selection.
func (*SoftwareRenderer) Resize ¶ added in v0.21.0
func (r *SoftwareRenderer) Resize(width, height int)
Resize updates the renderer dimensions. This should be called when the context is resized.
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 SolidPainter ¶ added in v0.24.0
type SolidPainter struct {
Color RGBA
}
SolidPainter fills all pixels with a single color (fastest path).
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 SurfaceTargetAware ¶ added in v0.28.0
SurfaceTargetAware is an optional interface for accelerators that support direct surface rendering. When SetSurfaceTarget is called with a non-nil view, the accelerator renders directly to the surface texture instead of reading back pixels to CPU. This eliminates the GPU->CPU->GPU round-trip for windowed rendering (ggcanvas + gogpu).
Call SetSurfaceTarget with nil to return to offscreen (readback) mode. The caller retains ownership of the surface view.
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
¶
- accelerator.go
- brush.go
- brush_custom.go
- color.go
- context.go
- context_clip.go
- context_image.go
- context_layer.go
- context_mask.go
- coverage_filler.go
- curve.go
- dash.go
- doc.go
- gradient.go
- gradient_linear.go
- gradient_radial.go
- gradient_sweep.go
- logger.go
- mask.go
- matrix.go
- options.go
- paint.go
- painter.go
- path.go
- path_builder.go
- path_ops.go
- pattern.go
- pipeline_mode.go
- pixmap.go
- point.go
- rasterizer_mode.go
- renderer.go
- sdf.go
- sdf_accelerator.go
- shape_detect.go
- shapes.go
- software.go
- solver.go
- stroke.go
- text.go
- vec.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
ggdemo
command
Command ggdemo demonstrates the gg 2D graphics library.
|
Command ggdemo demonstrates the gg 2D graphics library. |
|
examples
|
|
|
basic
command
|
|
|
bezier_test
command
Package main demonstrates smooth bezier curve rendering.
|
Package main demonstrates smooth bezier curve rendering. |
|
clipping
command
Package main demonstrates the clipping API in gogpu/gg.
|
Package main demonstrates the clipping API in gogpu/gg. |
|
color_emoji
command
Example: Color Emoji Extraction
|
Example: Color Emoji Extraction |
|
compute_pipeline
command
Command compute_pipeline is a visual demo comparing the Vello compute pipeline GPU output against the CPU reference implementation.
|
Command compute_pipeline is a visual demo comparing the Vello compute pipeline GPU output against the CPU reference implementation. |
|
gpu
command
Package main demonstrates GPU-accelerated 2D rendering with gg.
|
Package main demonstrates GPU-accelerated 2D rendering with gg. |
|
images
command
Package main demonstrates image drawing capabilities in gg.
|
Package main demonstrates image drawing capabilities in gg. |
|
recording
command
Example: Recording System
|
Example: Recording System |
|
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
|
|
|
text_transform
command
Package main demonstrates the CPU hybrid text transform pipeline (TEXT-002).
|
Package main demonstrates the CPU hybrid text transform pipeline (TEXT-002). |
|
Package gpu registers the GPU accelerator and coverage filler for hardware-accelerated rendering.
|
Package gpu registers the GPU accelerator and coverage filler for hardware-accelerated rendering. |
|
integration
|
|
|
ggcanvas
Package ggcanvas provides seamless integration between gg 2D graphics and gogpu GPU-accelerated windows.
|
Package ggcanvas provides seamless integration between gg 2D graphics and gogpu GPU-accelerated windows. |
|
internal
|
|
|
blend
Package blend implements advanced separable and non-separable blend modes.
|
Package blend implements advanced separable and non-separable blend modes. |
|
cache
Package cache provides generic, high-performance caching primitives.
|
Package cache provides generic, high-performance caching primitives. |
|
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. |
|
gpu
Package gpu provides a Pure Go GPU-accelerated rendering backend using gogpu/wgpu.
|
Package gpu provides a Pure Go GPU-accelerated rendering backend using gogpu/wgpu. |
|
gpu/tilecompute
Package tilecompute is a direct 1:1 port of Vello's CPU rasterization pipeline.
|
Package tilecompute is a direct 1:1 port of Vello's CPU rasterization pipeline. |
|
gpucore
Package gpucore provides shared GPU abstractions for the gg rendering pipeline.
|
Package gpucore provides shared GPU abstractions for the gg rendering pipeline. |
|
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 CPU-based rasterization primitives for gg.
|
Package raster provides CPU-based rasterization primitives for gg. |
|
stroke
Package stroke provides stroke expansion algorithms for converting stroked paths to filled outlines.
|
Package stroke provides stroke expansion algorithms for converting stroked paths to filled outlines. |
|
wide
Package wide provides SIMD-friendly wide types for batch pixel processing.
|
Package wide provides SIMD-friendly wide types for batch pixel processing. |
|
Package raster registers the CPU tile-based coverage filler for complex paths.
|
Package raster registers the CPU tile-based coverage filler for complex paths. |
|
Package recording provides types for recording drawing operations.
|
Package recording provides types for recording drawing operations. |
|
backends/raster
Package raster provides a raster backend for the recording system.
|
Package raster provides a raster backend for the recording system. |
|
Package render provides the integration layer between gg and GPU frameworks.
|
Package render provides the integration layer between gg and GPU frameworks. |
|
Package scene provides blend mode integration with internal/blend package.
|
Package scene provides blend mode integration with internal/blend package. |
|
Package surface provides a unified surface abstraction for 2D rendering.
|
Package surface provides a unified surface abstraction for 2D rendering. |
|
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. |