instructions

package
v1.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2025 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package instructions provides primitives for grouping and drawing bounded shapes together.

Package instructions provides primitives for drawing raster images with fitting, flipping, rotation, mask support, effects, and global opacity.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AlignItems

type AlignItems int

AlignItems controls cross-axis alignment of items within each line.

const (
	AlignItemsStart   AlignItems = iota // Align items to the start of the cross axis
	AlignItemsCenter                    // Align items to the cross-axis center
	AlignItemsEnd                       // Align items to the end of the cross axis
	AlignItemsStretch                   // Stretch items to fill the line’s cross size
)

type AlignText

type AlignText int

AlignText defines the horizontal alignment behavior of rendered lines.

const (
	// AlignTextLeft aligns text to the left edge.
	AlignTextLeft AlignText = iota
	// AlignTextCenter centers text horizontally within the line box.
	AlignTextCenter
	// AlignTextRight aligns text to the right edge.
	AlignTextRight
)

type AutoLayout

type AutoLayout struct {
	// contains filtered or unexported fields
}

AutoLayout is a flexible container that arranges child shapes according to Flexbox-like rules and draws them to an overlay image. It never modifies the base layer.

func NewAutoLayout

func NewAutoLayout(x, y int, style ContainerStyle) *AutoLayout

NewAutoLayout constructs a new flex container anchored at (x, y). If Display is not DisplayFlex, it is forced to DisplayFlex.

func (*AutoLayout) Add

func (al *AutoLayout) Add(s Shape, st ItemStyle) *AutoLayout

Add registers a child Shape with an optional ItemStyle. If the shape implements BoundedShape, its size and position are queried/updated automatically.

func (*AutoLayout) Draw

func (al *AutoLayout) Draw(base, overlay *image.RGBA)

Draw performs layout, sorts children by ZIndex, and draws each one in order. Shapes implementing Boundable receive SetBounds; else Position/Size are propagated if available.

func (*AutoLayout) SetStyle

func (al *AutoLayout) SetStyle(style ContainerStyle)

SetStyle replaces the container style and invalidates the current layout.

func (*AutoLayout) Size

func (al *AutoLayout) Size() *geom.Size

Size returns the outer dimensions of the container including padding. Triggers layout if needed.

type Boundable

type Boundable interface {
	SetBounds(x, y, w, h int)
}

Boundable is an optional capability: layout passes x,y,w,h in one call.

type BoundedShape

type BoundedShape interface {
	Shape

	// Size returns the intended width and height of the shape as a *geom.Size.
	// A zero value for either axis typically indicates that the shape should
	// determine its size automatically from its content or intrinsic geometry.
	Size() *geom.Size

	// Position returns the current top-left coordinate of the shape in
	// integer pixel units. This defines the anchor point used for rendering
	// and layout alignment.
	Position() (int, int)

	// SetPosition updates the shape’s anchor point to the given (x, y)
	// coordinate. This does not automatically trigger a redraw; the new
	// position is applied the next time Draw() is called.
	SetPosition(x, y int)
}

BoundedShape extends Shape with positional and dimensional metadata.

It introduces the concept of a rectangular bounding box, which defines both the size of the drawable object and its placement within a two-dimensional scene. This interface allows layout managers, compositors, and spatial algorithms to arrange and interact with multiple shapes consistently.

type Circle

type Circle struct {
	// contains filtered or unexported fields
}

Circle represents a drawable circle with fill, stroke, and optional effects.

func NewCircle

func NewCircle(x, y, radius float64) *Circle

NewCircle creates a new circle with given top-left and radius.

func (*Circle) AddEffect

func (c *Circle) AddEffect(e effects.Effect) *Circle

AddEffect adds a visual effect (blur, shadow, etc.) to the circle.

func (*Circle) AddEffects

func (c *Circle) AddEffects(es ...effects.Effect) *Circle

AddEffects adds multiple visual effects.

func (*Circle) Draw

func (c *Circle) Draw(base, overlay *image.RGBA)

Draw renders the circle to the overlay.

func (*Circle) Position

func (c *Circle) Position() (int, int)

Position returns top-left of bounding box.

func (*Circle) SetFillColor

func (c *Circle) SetFillColor(col patterns.Color) *Circle

SetFillColor sets solid fill color.

func (*Circle) SetFillPattern

func (c *Circle) SetFillPattern(p patterns.Pattern) *Circle

SetFillPattern sets custom fill pattern.

func (*Circle) SetLineWidth

func (c *Circle) SetLineWidth(width float64) *Circle

SetLineWidth sets stroke width.

func (*Circle) SetPosition

func (c *Circle) SetPosition(x, y int)

SetPosition sets top-left position of circle bounding box.

func (*Circle) SetRadius

func (c *Circle) SetRadius(r float64) *Circle

SetRadius sets circle radius.

func (*Circle) SetSteps

func (c *Circle) SetSteps(steps int) *Circle

SetSteps sets resolution for circle approximation.

func (*Circle) SetStrokeColor

func (c *Circle) SetStrokeColor(col patterns.Color) *Circle

SetStrokeColor sets solid stroke color.

func (*Circle) SetStrokePattern

func (c *Circle) SetStrokePattern(p patterns.Pattern) *Circle

SetStrokePattern sets custom stroke pattern.

func (*Circle) SetStrokePosition

func (c *Circle) SetStrokePosition(pos StrokePosition) *Circle

SetStrokePosition defines stroke alignment: inside, center, outside.

func (*Circle) Size

func (c *Circle) Size() *geom.Size

Size returns circle diameter as Size.

type ContainerStyle

type ContainerStyle struct {
	Display       Display
	Direction     FlexDirection
	Wrap          bool
	Padding       [4]int  // top, right, bottom, left
	Gap           Vector2 // gap.X = horizontal spacing, gap.Y = vertical spacing
	Justify       JustifyContent
	AlignItems    AlignItems
	AlignContent  AlignItems // cross-axis packing across multiple lines: Start/Center/End/Stretch
	Width, Height int        // container outer dimensions; 0 = auto by content
}

ContainerStyle defines CSS-like layout properties for an AutoLayout container. All numeric units are pixels. Width/Height of 0 mean "auto-size by content".

type Display

type Display int

Display describes the layout model used by a container. Only DisplayFlex is currently implemented but the enum allows future extensions.

const (
	// DisplayFlex enables Flexbox-style layout behavior.
	DisplayFlex Display = iota
)

type FillRule

type FillRule int

FillRule defines how interior regions of a path are determined.

const (
	// FillRuleWinding uses the non-zero winding rule.
	FillRuleWinding FillRule = iota
	// FillRuleEvenOdd uses the even-odd rule.
	FillRuleEvenOdd
)

type FitMode

type FitMode int

FitMode defines how the source image is resized to the target width/height.

const (
	// FitStretch stretches to exactly W×H. Aspect ratio is ignored.
	FitStretch FitMode = iota

	// FitContain preserves aspect ratio and fits fully inside W×H.
	// May leave empty space (letterbox/pillarbox). No cropping.
	FitContain

	// FitCover preserves aspect ratio and fills W×H completely.
	// Crops overflow. Good for thumbnails and covers.
	FitCover
)

type FlexDirection

type FlexDirection int

FlexDirection defines the orientation of the main axis in the flex container.

const (
	// Row lays out items horizontally, left-to-right by default.
	Row FlexDirection = iota
	// Column lays out items vertically, top-to-bottom by default.
	Column
)

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group represents a frame-like container of drawable shapes rendered as a composite. Children use local coordinates and are offset by (x, y). Optional clipping to the frame.

func NewGroup

func NewGroup() *Group

NewGroup creates a new Group with frame semantics by default.

func (*Group) AddInstruction

func (g *Group) AddInstruction(s BoundedShape)

AddInstruction adds a single shape.

func (*Group) AddInstructions

func (g *Group) AddInstructions(shapes ...BoundedShape)

AddInstructions adds multiple shapes.

func (*Group) Clear

func (g *Group) Clear()

Clear removes all shapes.

func (*Group) Draw

func (g *Group) Draw(base, overlay *image.RGBA)

func (*Group) Position

func (g *Group) Position() (int, int)

Position returns the current frame position.

func (*Group) SetClip

func (g *Group) SetClip(clip bool) *Group

SetClip enables or disables clipping to the frame rect.

func (*Group) SetFrameSize

func (g *Group) SetFrameSize(w, h int) *Group

SetFrameSize sets explicit frame size. Zero means auto from content.

func (*Group) SetPosition

func (g *Group) SetPosition(x, y int)

SetPosition sets frame position.

func (*Group) SetPositionChain

func (g *Group) SetPositionChain(x, y int) *Group

SetPositionChain sets position and returns the group for chaining.

func (*Group) Size

func (g *Group) Size() *geom.Size

Size returns composite size. - Explicit frame size if set, otherwise content bounds size.

type Image

type Image struct {
	// contains filtered or unexported fields
}

Image draws a raster with resize, flips, any-angle rotation, optional canvas expansion, effects, global opacity, and optional mask.

Fields are intentionally unexported. Use setters to keep state consistent.

func NewImage

func NewImage(src image.Image, x, y int) *Image

NewImage creates a new Image at (x, y) with safe defaults:

  • FitContain
  • opacity = 1
  • bg = Transparent
  • empty effects chain

func (*Image) AddEffect

func (im *Image) AddEffect(e effects.Effect) *Image

AddEffect appends a single effect to the pipeline.

func (*Image) AddEffects

func (im *Image) AddEffects(es ...effects.Effect) *Image

AddEffects appends multiple effects.

func (*Image) ClearMask

func (im *Image) ClearMask() *Image

ClearMask removes the current mask.

func (*Image) Draw

func (im *Image) Draw(_, overlay *image.RGBA)

Draw runs the pipeline and composites onto overlay.

func (*Image) Mirror

func (im *Image) Mirror(h, v bool) *Image

Mirror flips the image. h for horizontal, v for vertical.

func (*Image) Position

func (im *Image) Position() (int, int)

Position returns the destination top-left coordinate.

func (*Image) Rotate

func (im *Image) Rotate(deg float64) *Image

Rotate sets rotation angle in degrees.

func (*Image) SetBackground

func (im *Image) SetBackground(c patterns.Color) *Image

SetBackground sets the color sampled outside source bounds during rotation.

func (*Image) SetExpand

func (im *Image) SetExpand(b bool) *Image

SetExpand controls whether rotation expands the canvas to avoid cropping.

func (*Image) SetFit

func (im *Image) SetFit(f FitMode) *Image

SetFit selects Stretch/Contain/Cover.

func (*Image) SetFlip

func (im *Image) SetFlip(h, v bool) *Image

SetFlip is an alias of Mirror.

func (*Image) SetMaskFromShape

func (im *Image) SetMaskFromShape(s Shape) *Image

SetMaskFromShape renders a Shape into an RGBA mask matching the target size. If target size is zero, uses source bounds.

func (*Image) SetMaskImage

func (im *Image) SetMaskImage(m *image.RGBA) *Image

SetMaskImage assigns a mask image in destination space.

func (*Image) SetOpacity

func (im *Image) SetOpacity(o float64) *Image

SetOpacity sets global alpha in [0..1]. Values are clamped.

func (*Image) SetPosition

func (im *Image) SetPosition(x, y int)

SetPosition moves the layer to (x, y).

func (*Image) SetSize

func (im *Image) SetSize(w, h int) *Image

SetSize sets target width/height. Zero keeps that axis from the source.

func (*Image) Size

func (im *Image) Size() *geom.Size

Size returns the target size. Zero values mean "use source" for that axis.

type ItemStyle

type ItemStyle struct {
	Margin     [4]int // top, right, bottom, left
	Width      int    // fixed width; 0 = auto
	Height     int    // fixed height; 0 = auto
	FlexGrow   float64
	FlexShrink float64 // defaults to 1 if 0 and negative free space exists
	FlexBasis  int     // preferred main size in px; 0 = auto → width/height/intrinsic
	AlignSelf  *AlignItems

	// Positioning properties for absolute items.
	Position PositionType
	Top      *int
	Right    *int
	Bottom   *int
	Left     *int

	// Painting order (higher values drawn later).
	ZIndex int

	// IgnoreGapBefore skips the container gap directly before this item.
	// Affects line construction, wrapping, and final positioning.
	IgnoreGapBefore bool
}

ItemStyle defines layout behavior of a single child within a flex container.

type JustifyContent

type JustifyContent int

JustifyContent controls how free space is distributed along the main axis.

const (
	JustifyStart        JustifyContent = iota // Items packed at the start (default)
	JustifyCenter                             // Items centered along main axis
	JustifyEnd                                // Items packed at the end
	JustifySpaceBetween                       // Even spacing between items, none at ends
	JustifySpaceAround                        // Equal spacing around items, half-space at edges
	JustifySpaceEvenly                        // Equal spacing including container edges
)

type Layer

type Layer struct {
	// contains filtered or unexported fields
}

Layer represents a 2D drawable surface backed by an RGBA buffer. It provides methods to draw, export, and composite images.

func MustLoadLayerFromImagePath

func MustLoadLayerFromImagePath(path string) *Layer

MustLoadLayerFromImagePath loads a PNG or JPEG image from the specified file path and returns it as a Layer. It panics if the file cannot be opened, decoded, or if the format is unsupported. Intended for initialization code, tests, or tools where image load failures are considered fatal.

func NewLayer

func NewLayer(width, height int) *Layer

NewLayer creates a new empty Layer with the specified width and height. The underlying image buffer is initialized as a blank RGBA canvas.

func NewLayerFromImage

func NewLayerFromImage(src image.Image) *Layer

NewLayerFromImage creates a new Layer from any image.Image instance. The input image is converted to RGBA format if necessary.

func NewLayerFromImagePath

func NewLayerFromImagePath(path string) (*Layer, error)

NewLayerFromImagePath loads an image from the given file path. Only PNG and JPEG formats are allowed.

func NewLayerFromRGBA

func NewLayerFromRGBA(rgba *image.RGBA) *Layer

NewLayerFromRGBA creates a new Layer from an existing *image.RGBA buffer. The Layer will share the same underlying pixel data as the provided buffer.

func (*Layer) AddLayer

func (l *Layer) AddLayer(layer *Layer, x, y int) *Layer

AddLayer composites another Layer on top of the current one at the specified coordinates. The source Layer is drawn using the Over operator, preserving transparency.

func (*Layer) Draw

func (l *Layer) Draw(_, overlay *image.RGBA)

Draw renders this Layer’s contents onto another base and overlay image.

The method composites the layer’s RGBA data into the overlay image at the current (x, y) position. This allows a Layer to act as a drawable Shape within higher-level containers or layouts.

func (*Layer) Export

func (l *Layer) Export(path string) error

Export automatically determines the file format (PNG or JPEG) based on the file extension. Supported extensions: .png, .jpg, .jpeg.

func (*Layer) ExportBytes

func (l *Layer) ExportBytes(level png.CompressionLevel) ([]byte, error)

ExportBytes encodes the current Layer as PNG and returns the raw byte slice. Useful for in-memory exports, HTTP responses, or further processing.

func (*Layer) ExportJPEG

func (l *Layer) ExportJPEG(path string, quality int) error

ExportJPEG saves the Layer as a JPEG image to the specified file path. The quality value must be between 0 and 100.

func (*Layer) ExportPNG

func (l *Layer) ExportPNG(path string, level png.CompressionLevel) error

ExportPNG saves the Layer as a PNG image to the specified file path. The compression level controls the output file size and encoding speed.

func (*Layer) Image

func (l *Layer) Image() *image.RGBA

Image returns the underlying *image.RGBA buffer of the Layer.

func (*Layer) LoadInstruction

func (l *Layer) LoadInstruction(shape Shape)

LoadInstruction executes a single drawing instruction on the Layer. The instruction defines its own drawing behavior through the Shape interface.

func (*Layer) LoadInstructions

func (l *Layer) LoadInstructions(shapes ...Shape)

LoadInstructions executes a sequence of drawing instructions in order. Optimized for batch operations while maintaining predictable execution order.

func (*Layer) Position

func (l *Layer) Position() (int, int)

Position returns the top-left corner of the Layer in parent coordinates.

func (*Layer) SetBounds

func (l *Layer) SetBounds(x, y, width, height int)

SetBounds sets the Layer’s position and visible bounds. The size change is clamped to the current buffer capacity and does not resample or reallocate pixels. Only the bounds are adjusted; content stays intact.

func (*Layer) SetBoundsChain

func (l *Layer) SetBoundsChain(x, y, width, height int) *Layer

SetBoundsChain sets position and size, clamps size to buffer limits, and returns the Layer. Identical to SetBounds but chainable.

func (*Layer) SetPosition

func (l *Layer) SetPosition(x, y int)

SetPosition sets the Layer’s position in integer coordinates.

func (*Layer) SetPositionChain

func (l *Layer) SetPositionChain(x, y int) *Layer

SetPositionChain sets position and returns the same Layer for method chaining.

func (*Layer) SetSize

func (l *Layer) SetSize(w, h int)

SetSize adjusts the Layer's visible bounds to the requested width and height without resampling or reallocating pixels. The bounds are clamped to the current backing buffer capacity to avoid expansion. Content is not modified.

func (*Layer) SetSizeChain

func (l *Layer) SetSizeChain(w, h int) *Layer

SetSizeChain sets the visible bounds to width and height and returns the Layer. Identical to SetSize but chainable.

func (*Layer) Size

func (l *Layer) Size() *geom.Size

Size returns the dimensions of the current Layer as a *geom.Size object.

type Line

type Line struct {
	// contains filtered or unexported fields
}

Line is the public facade that exposes a vector drawing API.

func NewLine

func NewLine() *Line

NewLine creates a new Line with default styles and identity transform.

func (*Line) ClearPath

func (l *Line) ClearPath() *Line

ClearPath clears all paths and resets subpath state.

func (*Line) ClipPreserve

func (l *Line) ClipPreserve() *Line

ClipPreserve updates the clip mask by rasterizing the current fill path.

func (*Line) ClosePath

func (l *Line) ClosePath() *Line

ClosePath closes the current subpath by drawing a segment to the start point.

func (*Line) CubicTo

func (l *Line) CubicTo(x1, y1, x2, y2, x3, y3 float64) *Line

CubicTo adds a cubic Bézier curve and discretizes it to a polyline.

func (*Line) Draw

func (l *Line) Draw(base, overlay *image.RGBA)

Draw executes all pending raster operations onto the provided RGBA image.

func (*Line) Fill

func (l *Line) Fill() *Line

Fill fills the current path and then clears it.

func (*Line) FillPreserve

func (l *Line) FillPreserve() *Line

FillPreserve schedules a fill rasterization of the current path without clearing it.

func (*Line) LineTo

func (l *Line) LineTo(x, y float64) *Line

LineTo adds a straight segment to (x, y). Starts a subpath if none exists.

func (*Line) MoveTo

func (l *Line) MoveTo(x, y float64) *Line

MoveTo starts a new subpath at (x, y). Closes the previous fill subpath if needed.

func (*Line) NewSubPath

func (l *Line) NewSubPath() *Line

NewSubPath ends the current fill subpath and prepares for a new one.

func (*Line) QuadraticTo

func (l *Line) QuadraticTo(x1, y1, x2, y2 float64) *Line

QuadraticTo adds a quadratic Bézier curve and discretizes it for dashing.

func (*Line) ResetMask

func (l *Line) ResetMask() *Line

ResetMask clears any active clip mask.

func (*Line) ResetMatrix

func (l *Line) ResetMatrix() *Line

ResetMatrix resets the transform matrix to identity.

func (*Line) SetDashOffset

func (l *Line) SetDashOffset(off float64) *Line

SetDashOffset sets the initial dash offset along the path.

func (*Line) SetDashes

func (l *Line) SetDashes(d []float64) *Line

SetDashes sets dash lengths alternating on/off along the stroke.

func (*Line) SetFillPattern

func (l *Line) SetFillPattern(p patterns.Pattern) *Line

SetFillPattern sets the pattern used to paint fills.

func (*Line) SetFillRule

func (l *Line) SetFillRule(r FillRule) *Line

SetFillRule sets the fill rule used to determine interior.

func (*Line) SetLineCap

func (l *Line) SetLineCap(c LineCap) *Line

SetLineCap sets the cap style for strokes.

func (*Line) SetLineJoin

func (l *Line) SetLineJoin(j LineJoin) *Line

SetLineJoin sets the join style for strokes.

func (*Line) SetLineWidth

func (l *Line) SetLineWidth(w float64) *Line

SetLineWidth sets the stroke width in pixels.

func (*Line) SetStrokePattern

func (l *Line) SetStrokePattern(p patterns.Pattern) *Line

SetStrokePattern sets the pattern used to paint strokes.

func (*Line) Stroke

func (l *Line) Stroke() *Line

Stroke strokes the current path and then clears it.

func (*Line) StrokePreserve

func (l *Line) StrokePreserve() *Line

StrokePreserve schedules a stroke rasterization of the current path without clearing it.

func (*Line) WithMatrix

func (l *Line) WithMatrix(m geom.Matrix) *Line

WithMatrix sets the current transform matrix.

type LineCap

type LineCap int

LineCap defines how the end of a stroked line is rendered.

const (
	// LineCapRound renders rounded end caps.
	LineCapRound LineCap = iota
	// LineCapButt renders flat end caps at the exact end of the path.
	LineCapButt
	// LineCapSquare renders square end caps that extend by half the line width.
	LineCapSquare
)

type LineJoin

type LineJoin int

LineJoin defines how the junction between two line segments is rendered.

const (
	// LineJoinRound renders rounded joins between segments.
	LineJoinRound LineJoin = iota
	// LineJoinBevel renders a beveled (cut-off) corner at joins.
	LineJoinBevel
)

type Point

type Point struct {
	X, Y float64
	// contains filtered or unexported fields
}

Point represents a 2D coordinate or vector using float64 precision. It also holds an optional color used for rendering operations.

func CubicBezier

func CubicBezier(x0, y0, x1, y1, x2, y2, x3, y3 float64) []*Point

CubicBezier discretizes a cubic Bézier into a sequence of points.

func NewPoint

func NewPoint(x, y float64) *Point

NewPoint creates a new Point at (x, y) with the default color black.

func QuadraticBezier

func QuadraticBezier(x0, y0, x1, y1, x2, y2 float64) []*Point

QuadraticBezier discretizes a quadratic Bézier into a sequence of points.

func (*Point) Add

func (p *Point) Add(q Point) Point

Add returns the vector sum of p and q (p + q).

func (*Point) Angle

func (p *Point) Angle(q Point) float64

Angle returns the angle in radians between vectors p and q, computed using the dot product. Returns 0 if either vector has zero length.

func (*Point) Color

func (p *Point) Color() patterns.Color

Color returns the current color assigned to the Point.

func (*Point) Distance

func (p *Point) Distance(q *Point) float64

Distance returns the Euclidean distance between the current Point (p) and another Point (q).

func (*Point) Dot

func (p *Point) Dot(q Point) float64

Dot returns the dot product of p and q, commonly used for angle and projection calculations.

func (*Point) Draw

func (p *Point) Draw(_, overlay *image.RGBA)

Draw renders a single pixel representing the Point’s location on the given overlay image, if it lies within bounds. The base image parameter is ignored for consistency with other Draw methods.

func (*Point) Fixed

func (p *Point) Fixed() fixed.Point26_6

Fixed converts the Point to a fixed-point coordinate (26.6 format). Commonly used for subpixel-accurate rendering and rasterization.

func (*Point) Interpolate

func (p *Point) Interpolate(q *Point, t float64) *Point

Interpolate returns a linearly interpolated point between p and q. The parameter t (0–1) determines the position: t=0 → p, t=1 → q.

func (*Point) Length

func (p *Point) Length() float64

Length returns the magnitude of the vector represented by the Point (distance from the origin to the point).

func (*Point) Midpoint

func (p *Point) Midpoint(q Point) Point

Midpoint returns the point exactly halfway between p and q.

func (*Point) Normalize

func (p *Point) Normalize() Point

Normalize returns a unit vector (length = 1) pointing in the same direction as p. If p is zero-length, it returns (0, 0).

func (*Point) Rotate

func (p *Point) Rotate(angle float64) *Point

Rotate returns a new Point rotated around the origin by the given angle in radians. Positive values rotate counterclockwise.

func (*Point) Scale

func (p *Point) Scale(factor float64) Point

Scale returns a new Point scaled by the specified factor. Both X and Y coordinates are multiplied by factor.

func (*Point) SetColor

func (p *Point) SetColor(c patterns.Color) *Point

SetColor assigns a drawing color to the Point and returns itself for method chaining.

func (*Point) Sub

func (p *Point) Sub(q Point) Point

Sub returns the vector difference between p and q (p − q).

type PositionType

type PositionType int

PositionType indicates whether an item participates in normal layout flow.

const (
	// PosRelative participates in normal flow (default).
	PosRelative PositionType = iota
	// PosAbsolute is removed from flow and positioned relative to the container padding box.
	PosAbsolute
)

type Rectangle

type Rectangle struct {
	// contains filtered or unexported fields
}

Rectangle represents a drawable rectangle with per-corner rounding, fill, and stroke.

func NewRectangle

func NewRectangle(x, y, width, height float64) *Rectangle

NewRectangle creates a new rectangle with the given position and size.

func (*Rectangle) AddEffect

func (r *Rectangle) AddEffect(e effects.Effect) *Rectangle

AddEffect attaches a visual effect to the rectangle rendering pipeline.

The added effect will be stored inside the internal effect container `t.effects` and applied automatically during rendering:

  • Pre-effects (e.IsPre() == true) execute before text drawing.
  • Post-effects (e.IsPre() == false) execute after text drawing.

This allows chaining multiple visual transformations such as drop shadows, layer blurs, and noise filters.

Example:

rectangle.AddEffect(effects.NewDropShadow(0, 4, 4, 0, colors.Black, 0.25))

func (*Rectangle) AddEffects

func (r *Rectangle) AddEffects(es ...effects.Effect) *Rectangle

AddEffects attaches multiple visual effects to the pipeline.

func (*Rectangle) Draw

func (r *Rectangle) Draw(base, overlay *image.RGBA)

Draw renders the rectangle with stroke alignment (inside, center, outside).

func (*Rectangle) Position

func (r *Rectangle) Position() (int, int)

Position returns the top-left coordinate where the layer is drawn.

func (*Rectangle) SetCornerRadii

func (r *Rectangle) SetCornerRadii(tl, tr, br, bl float64) *Rectangle

SetCornerRadii sets per-corner radii: top-left, top-right, bottom-right, bottom-left.

func (*Rectangle) SetFillColor

func (r *Rectangle) SetFillColor(c patterns.Color) *Rectangle

SetFillColor sets solid fill colorPattern.

func (*Rectangle) SetFillPattern

func (r *Rectangle) SetFillPattern(p patterns.Pattern) *Rectangle

SetFillPattern sets fill pattern.

func (*Rectangle) SetLineWidth

func (r *Rectangle) SetLineWidth(width float64) *Rectangle

SetLineWidth sets stroke width.

func (*Rectangle) SetPosition

func (r *Rectangle) SetPosition(x, y int)

SetPosition sets the rectangle’s top-left corner.

func (*Rectangle) SetRadius

func (r *Rectangle) SetRadius(radius float64) *Rectangle

SetRadius sets uniform corner radius for all corners.

func (*Rectangle) SetRoundedSteps

func (r *Rectangle) SetRoundedSteps(steps int) *Rectangle

SetRoundedSteps sets resolution of rounded arcs.

func (*Rectangle) SetSize

func (r *Rectangle) SetSize(width, height float64) *Rectangle

SetSize sets width and height.

func (*Rectangle) SetStrokeColor

func (r *Rectangle) SetStrokeColor(c patterns.Color) *Rectangle

SetStrokeColor sets solid stroke colorPattern.

func (*Rectangle) SetStrokePattern

func (r *Rectangle) SetStrokePattern(p patterns.Pattern) *Rectangle

SetStrokePattern sets stroke pattern.

func (*Rectangle) SetStrokePosition

func (r *Rectangle) SetStrokePosition(pos StrokePosition) *Rectangle

SetStrokePosition defines whether stroke is drawn inside, centered, or outside the border.

func (*Rectangle) Size

func (r *Rectangle) Size() *geom.Size

Size returns rectangle size.

type Resizable

type Resizable interface {
	SetSize(w, h int)
}

Resizable is an optional capability: layout passes resolved size to the shape.

type Shape

type Shape interface {
	// Draw renders the shape’s visual representation into the given
	// base and overlay image buffers. Implementations decide how to
	// blend, composite, or otherwise use the provided layers.
	Draw(base, overlay *image.RGBA)
}

Shape defines the minimal contract for any drawable visual entity or rendering instruction in the system.

Implementations of Shape are responsible for drawing visual output onto one or both of the provided RGBA image buffers. These buffers represent different layers in the rendering pipeline:

  • base: The read-only background image. Can be used for sampling or blending reference data but should not be modified directly.
  • overlay: The active target buffer where the shape should render its visual output.

The drawing function should confine its modifications to the intended area of the shape and must not alter unrelated pixels outside its bounds. Each Shape implementation defines its own compositing, blending, and color behavior.

type StrokePosition

type StrokePosition int

StrokePosition defines stroke alignment relative to the rectangle border.

const (
	StrokeInside StrokePosition = iota
	StrokeCenter
	StrokeOutside
)

func (StrokePosition) Outset

func (s StrokePosition) Outset(lineWidth float64) float64

type Text

type Text struct {
	// contains filtered or unexported fields
}

Text describes a multi-line text block capable of wrapping, aligning, scaling, and applying stroke/fill effects.

Features include:

  • Word or symbol wrapping with optional hyphenation.
  • Left/center/right alignment within fixed width or anchor-based layout.
  • Progressive per-line scaling for dynamic typography.
  • Automatic or manual line spacing.
  • Pattern or gradient fill based on canvas coordinates.
  • Morphological stroke expansion using alpha dilation.
  • Pre- and post-processing effects via a flexible effect container.

func NewText

func NewText(text string, x, y float64, font *render.Font) *Text

NewText constructs a Text instance with default configuration. Defaults:

  • WrapByWord and AlignTextLeft
  • No stroke or fill pattern
  • lineSpacing = 0 → automatic by font metrics
  • maxWidth = 0 → no wrapping, anchor-based alignment

func (*Text) AddEffect

func (t *Text) AddEffect(e effects.Effect) *Text

AddEffect adds a single post-processing effect to the text rendering pipeline.

func (*Text) AddEffects

func (t *Text) AddEffects(es ...effects.Effect) *Text

AddEffects appends multiple effects to the rendering pipeline in order.

func (*Text) Draw

func (t *Text) Draw(base, overlay *image.RGBA)

Draw renders the text block into the given base and overlay images. The method performs optional stroke, fill, and post-processing effects.

func (*Text) Position

func (t *Text) Position() (int, int)

Position returns the integer coordinates where the text block originates.

func (*Text) SetAlign

func (t *Text) SetAlign(a AlignText) *Text

SetAlign configures horizontal line alignment.

func (*Text) SetColorPattern

func (t *Text) SetColorPattern(p patterns.Pattern) *Text

SetColorPattern applies a pattern or gradient fill for text glyphs.

func (*Text) SetLineSpacing

func (t *Text) SetLineSpacing(percent float64) *Text

SetLineSpacing defines custom spacing as a percentage of line height.

func (*Text) SetMaxLines

func (t *Text) SetMaxLines(n int) *Text

SetMaxLines limits the number of rendered lines. Zero means no limit.

func (*Text) SetMaxWidth

func (t *Text) SetMaxWidth(w float64) *Text

SetMaxWidth limits the maximum text box width in pixels. A value of 0 disables wrapping and aligns relative to anchor coordinates.

func (*Text) SetPosition

func (t *Text) SetPosition(x, y int)

SetPosition updates the anchor coordinates of the text block.

func (*Text) SetScaleStep

func (t *Text) SetScaleStep(pt float64) *Text

SetScaleStep applies a per-line font size increment (in points). Positive values enlarge text progressively; negative values shrink it.

func (*Text) SetSolidColor

func (t *Text) SetSolidColor(c patterns.Color) *Text

SetSolidColor applies a uniform color fill by generating a solid pattern.

func (*Text) SetStrokeWithColor

func (t *Text) SetStrokeWithColor(c patterns.Color, width float64) *Text

SetStrokeWithColor defines a stroke using a solid color pattern.

func (*Text) SetStrokeWithPattern

func (t *Text) SetStrokeWithPattern(p patterns.Pattern, width float64) *Text

SetStrokeWithPattern defines a stroke using a color or gradient pattern.

func (*Text) SetWrap

func (t *Text) SetWrap(mode WrapMode, symbol string) *Text

SetWrap sets wrapping mode and hyphenation symbol.

func (*Text) SetWrapMode

func (t *Text) SetWrapMode(mode WrapMode) *Text

SetWrapMode changes wrapping behavior without modifying the hyphenation symbol.

func (*Text) SetWrapSymbol

func (t *Text) SetWrapSymbol(sym string) *Text

SetWrapSymbol defines a custom symbol used during symbol-based wrapping. Falls back to "-" when an empty string is provided.

func (*Text) Size

func (t *Text) Size() *geom.Size

Size computes the bounding box of the rendered text. Returns zero if text or font is undefined.

type Vector2

type Vector2 = Point

Vector2 is an alias for Point, used for semantic clarity when representing mathematical vectors instead of geometric coordinates.

func NewVec2

func NewVec2(x, y float64) *Vector2

NewVec2 returns a new Vector2 (alias of Point) initialized with the given x and y values. The default color is black.

type WrapMode

type WrapMode int

WrapMode defines how text lines are broken when exceeding maximum width.

const (
	// WrapByWord breaks lines at whitespace boundaries only.
	WrapByWord WrapMode = iota
	// WrapBySymbol breaks lines at character level and optionally inserts a hyphenation symbol.
	WrapBySymbol
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL