gfx

package
v0.15.5 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: EPL-2.0 Imports: 19 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gfx is an experimental retained 2D canvas for gowt: a tree of nodes holding recorded Pictures, a compositor that shows it from cached tiles, and the geometry under both.

The package is pure Go and builds on every OS. Rasterizers and layer hosts live in sub-packages: gfx/cg (macOS), gfx/cairo (Linux), gfx/d2d (Windows), gfx/view (the gowt widget), gfx/offscreen (PNG without a window), gfx/layout (auto-layout) and gfx/pen (.pen designs). Most programs need only gfx, gfx/view or gfx/offscreen. The API may change without notice; docs/gfx.md has a quick start and the overview.

  • Path, Measure: curves, exact bounds, flattening, length, point and tangent by length, nearest point, split.
  • Recorder and Picture: drawing commands in a compact byte stream, with bounds, gradients, clips, layers with alpha, shadows, images and text measured by the backend.
  • Scene and Node: transforms relative to the parent, opacity, clips, order among siblings, a grid index, hit-testing that honors ancestor clips, and transactions (Scene.Update, applied by Scene.Commit) callable from any goroutine.
  • Compositor: static tiles drawn by a bounded worker pool, an active layer for dragged nodes, an overlay of animated Sprites, all placed on whole device pixels on a Host.
  • RenderSubtree, Picture.WriteSVG and WriteSubtreeSVG: output without a window.
Example

A scene holds nodes; a node draws a Picture recorded in its own coordinates. Changes go through Update and take effect at Commit, which a window does every frame.

package main

import (
	"fmt"

	"github.com/haiodo/gowt/gfx"
)

func main() {
	rec := gfx.NewRecorder()
	rec.FillRRect(gfx.R(0, 0, 120, 60), 8, gfx.RGB(30, 120, 220))
	rec.Text("Hello", 12, 36, gfx.Font{Size: 14}, gfx.White)

	card := gfx.NewNode(1)
	scene := gfx.NewScene()
	scene.Update(func(tx *gfx.Tx) {
		tx.Add(nil, card)
		tx.SetPicture(card, rec.Finish())
		tx.Move(card, 100, 50)
	})
	scene.Commit() // without a window nobody else does

	fmt.Println(scene.HitTest(gfx.Point{X: 110, Y: 60}, 0).ID(), scene.HitTest(gfx.Point{X: 0, Y: 0}, 0) == nil)
	fmt.Println(card.Bounds().Min, scene.Node(1) == card)
}
Output:
1 true
{100 50} true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	Black = Color{A: 1}
	White = Color{R: 1, G: 1, B: 1, A: 1}
)

Black and White are the opaque extremes.

Functions

func Release

func Release(img Image)

Release frees an Image a backend made, if it has anything to free.

func WritePicturePDF

func WritePicturePDF(r PDFRenderer, w io.Writer, p *Picture, o PDFOptions) error

WritePicturePDF writes one picture, the whole of its bounds, as a one-page PDF.

func WriteSubtreePDF

func WriteSubtreePDF(r PDFRenderer, w io.Writer, s *Scene, root *Node, area Rect, o PDFOptions) error

WriteSubtreePDF writes the subtree of root, as RenderSubtree draws it, as a one-page PDF; a nil root writes the whole scene. area is the scene rectangle to write, or the zero Rect for the subtree bounds. It commits the scene's pending changes first and needs no window.

func WriteSubtreeSVG

func WriteSubtreeSVG(out io.Writer, s *Scene, root *Node, area Rect, scale float64) error

WriteSubtreeSVG writes the subtree of root, as RenderSubtree draws it, as an SVG document; a nil root writes the whole scene. area is the scene rectangle to write, or the zero Rect for the subtree bounds.

func WriteSubtreeSVGWith

func WriteSubtreeSVGWith(out io.Writer, s *Scene, root *Node, area Rect, scale float64, opt SVGOptions) error

WriteSubtreeSVGWith is WriteSubtreeSVG with opt.

Types

type Affine

type Affine [6]float64

Affine is [a b c d tx ty]: x' = a*x + c*y + tx, y' = b*x + d*y + ty.

func Identity

func Identity() Affine

Identity returns the transform that changes nothing.

func RotateBy

func RotateBy(a float64) Affine

RotateBy returns the transform that rotates by a radians about the origin.

func ScaleBy

func ScaleBy(x, y float64) Affine

ScaleBy returns the transform that scales by x and y about the origin.

func TranslateBy

func TranslateBy(x, y float64) Affine

TranslateBy returns the transform that moves by (x, y).

func (Affine) Apply

func (m Affine) Apply(p Point) Point

Apply returns p transformed by m.

func (Affine) Bounds

func (m Affine) Bounds(r Rect) Rect

Bounds returns the bounding box of r transformed by m.

func (Affine) Det

func (m Affine) Det() float64

Det is the determinant of the linear part.

func (Affine) Invert

func (m Affine) Invert() (inv Affine, ok bool)

Invert returns the inverse transform; ok is false for a singular matrix.

func (Affine) Mul

func (m Affine) Mul(n Affine) Affine

Mul returns the transform that applies n first, then m.

func (Affine) SameLinear

func (m Affine) SameLinear(n Affine) bool

SameLinear reports whether m and n differ at most in translation.

func (Affine) Scale

func (m Affine) Scale() float64

Scale is the factor by which m scales lengths on average: sqrt(|det|).

type Camera

type Camera struct {
	Origin Point
	Zoom   float64
}

Camera maps the scene to the view: Origin is the scene point at the view's top left, Zoom is view points per scene unit.

type Cap

type Cap uint8

Cap is the shape of the ends of a stroked line.

const (
	CapButt Cap = iota
	CapRound
	CapSquare
)

The line caps: flat at the end, round, or square past the end by half the width.

type Clip

type Clip struct {
	M      Affine
	Kind   ClipKind
	Rect   Rect
	Radius float64
	Path   *Path
}

Clip is one clip of an Item: the shape in the coordinates of the transform M, which maps them to the target's scene space.

type ClipKind

type ClipKind uint8

ClipKind is the shape of a node clip.

const (
	ClipNone ClipKind = iota
	ClipRect
	ClipRRect
	ClipPath
)

The kinds of node clip.

type Color

type Color struct{ R, G, B, A float64 }

Color is non-premultiplied RGBA in 0..1.

func RGB

func RGB(r, g, b uint8) Color

RGB returns the opaque color of three 8-bit channels, the way gowt.RGB writes them.

func RGBA

func RGBA(r, g, b uint8, a float64) Color

RGBA is RGB with an alpha of 0..1.

func (Color) WithAlpha

func (c Color) WithAlpha(a float64) Color

WithAlpha returns c with alpha a (0..1).

type Compositor

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

Compositor shows a Scene on a Host: static tiles drawn by a pool of workers, an active layer of lifted nodes (sprites that follow their node), and an overlay of free sprites. Everything but NeedsFrame and the Sprite methods is for the goroutine that runs Frame.

func NewCompositor

func NewCompositor(s *Scene, r Renderer, h Host, o Options) *Compositor

NewCompositor returns a compositor that draws s with r onto h. Most apps get one from view.New.

func (*Compositor) Camera

func (c *Compositor) Camera() Camera

Camera returns the current camera.

func (*Compositor) Close

func (c *Compositor) Close()

Close stops the workers and removes every layer.

func (*Compositor) Frame

func (c *Compositor) Frame(fi FrameInfo)

Frame brings the host up to date for the frame described by fi. It runs on the UI goroutine.

func (*Compositor) FrameTime

func (c *Compositor) FrameTime() FrameInfo

FrameTime is the clock of the Frame being or last run.

func (*Compositor) HUD

func (c *Compositor) HUD() *Scene

HUD returns the heads-up scene, made on the first call: a scene in view points (y down, the origin at the top left of the view) that is drawn over everything, tiles, lifted nodes and sprites, and does not move or zoom with the camera. Use it for indicators at the canvas edge, rulers, a minimap and text overlays. It is an ordinary Scene: nodes, pictures, transforms, clips, opacity and Update from any goroutine.

The compositor draws the scene into one image that covers the bounds of its content inside the view, and draws it again only when the scene changes or the view size or backing scale does, so a HUD costs nothing in a frame that changes nothing in it. Do not give a node over the whole view a picture to catch the pointer: set the node's shape with HitNone or a real shape, since HitBounds takes the pointer wherever the node's bounds are, see HUDHit.

func (*Compositor) HUDHit

func (c *Compositor) HUDHit(p Point, tol float64) *Node

HUDHit returns the topmost HUD node under the view point p, or nil. tol is the stroke tolerance and bounds slack in points. It sees the HUD as of the last Frame, and it comes before the scene in view.Pointer: when it returns a node the pointer is over the HUD.

func (*Compositor) Land

func (c *Compositor) Land(nodes ...*Node)

Land returns the nodes to the static tiles. Their sprites stay until the tiles under them are redrawn.

func (*Compositor) Lift

func (c *Compositor) Lift(nodes ...*Node)

Lift moves nodes, with their subtrees, from the static tiles to the active layer: each becomes a sprite that follows its node without redrawing tiles. Nodes whose picture changes every frame, such as connectors, are redrawn into their sprite on each Frame. Call Land when the drag ends.

func (*Compositor) NeedsFrame

func (c *Compositor) NeedsFrame() bool

NeedsFrame reports whether a Frame would change anything: safe from any goroutine, cheap enough for a display-link callback to call on every tick.

func (*Compositor) NewSprite

func (c *Compositor) NewSprite(pic *Picture, space Space, pos Point) *Sprite

NewSprite puts pic on the overlay at pos, above the sprites made before it.

func (*Compositor) OnFrame

func (c *Compositor) OnFrame(f func(FrameInfo))

OnFrame sets f to run at the start of every Frame with the frame clock, before the scene's transactions are applied: the place to advance model animations. While f is set, NeedsFrame is true and the display link runs a frame on every tick; OnFrame(nil) lets an idle scene stop ticking.

func (*Compositor) OnViewport

func (c *Compositor) OnViewport(f func(w, h, dpr float64))

OnViewport sets f to run on the Frame goroutine, at the start of the HUD step, with the view size in points and the backing scale: once at the first Frame after it is set and again whenever either changes. Place the HUD nodes there (an indicator on the right edge moves with the width); the changes it makes are drawn in the same frame.

func (*Compositor) SceneAt

func (c *Compositor) SceneAt(p Point) Point

SceneAt maps a view point to a scene point.

func (*Compositor) SetCamera

func (c *Compositor) SetCamera(cam Camera)

SetCamera moves and zooms the view; Zoom is view points per scene unit.

func (*Compositor) SetViewport

func (c *Compositor) SetViewport(w, h, dpr float64)

SetViewport sets the view size in points and the device pixels per point.

func (*Compositor) Stats

func (c *Compositor) Stats() Stats

Stats returns the counters of the last frame and the totals so far.

func (*Compositor) ViewAt

func (c *Compositor) ViewAt(p Point) Point

ViewAt maps a scene point to a view point.

func (*Compositor) Viewport

func (c *Compositor) Viewport() (w, h, dpr float64)

Viewport returns the view size in points and the device pixels per point, as of the last SetViewport.

func (*Compositor) Workers

func (c *Compositor) Workers() int

Workers is the number of tile rasterizer goroutines.

func (*Compositor) ZoomAt

func (c *Compositor) ZoomAt(f float64, p Point)

ZoomAt multiplies the zoom by f keeping the scene point under the view point p where it is.

type Document

type Document interface {
	// NewPage ends the page before it and starts one of wpt by hpt points (1/72 inch).
	NewPage(wpt, hpt float64) Page
	// Close ends the last page and finishes the output. The Document is not used afterwards.
	Close() error
}

Document is a paged vector output, a PDF file. A PDFRenderer makes one.

type Easing

type Easing func(t float64) float64

Easing maps linear progress 0..1 to eased progress; it must give 0 at 0 and 1 at 1.

var (
	Linear    Easing = func(t float64) float64 { return t }
	EaseIn    Easing = func(t float64) float64 { return t * t * t }
	EaseOut   Easing = func(t float64) float64 { u := 1 - t; return 1 - u*u*u }
	EaseInOut Easing = func(t float64) float64 {
		if t < 0.5 {
			return 4 * t * t * t
		}
		u := -2*t + 2
		return 1 - u*u*u/2
	}
)

The easings. Linear is constant speed; EaseIn starts slow, EaseOut ends slow, EaseInOut does both.

func CubicBezier

func CubicBezier(x1, y1, x2, y2 float64) Easing

CubicBezier is the CSS timing function cubic-bezier(x1, y1, x2, y2).

type EstimateText

type EstimateText struct{}

EstimateText is the measurer used until a backend sets one: 0.6 em per rune, ascent 0.8 em, descent 0.25 em.

func (EstimateText) MeasureText

func (EstimateText) MeasureText(s string, f Font) TextMetrics

MeasureText estimates the size of s from the number of runes; Spacing counts for each of them.

type Font

type Font struct {
	Name    string
	Family  string
	Weight  int
	Italic  bool
	Size    float64
	Spacing float64
}

Font is a face, a size in points and a tracking.

Name is an exact face name (a PostScript name such as "IBMPlexSans-SmBld", or a family); when it is set, Family, Weight and Italic are not read. Without a Name the backend picks the face of Family whose weight is closest to Weight (CSS scale 100..900, 0 means 400) and whose slant matches Italic, among installed fonts and those registered with RegisterFonts. An empty Family or one the backend does not have is the default sans face of the backend, at that weight and slant.

Spacing is added after every character, in points, in drawing and in measuring: the width of a line is its natural width plus Spacing for each rune, the last one included, as in CSS.

type FrameInfo

type FrameInfo struct {
	Time     time.Duration
	Interval time.Duration // the display's refresh period, 0 if unknown
	Seq      uint64
}

FrameInfo describes one display frame. Time is the frame clock, the time the frame will be shown, counted from an arbitrary start; only differences mean anything. Animations run on it.

type Gradient

type Gradient struct {
	Kind   GradientKind
	P0, P1 Point
	R0, R1 float64
	Stops  []Stop
}

Gradient is linear from P0 to P1, or radial from the circle (P0, R0) to the circle (P1, R1). Its coordinates are in the space of the shape that uses it.

func NewLinearGradient

func NewLinearGradient(p0, p1 Point, stops ...Stop) *Gradient

NewLinearGradient returns a gradient along the line from p0 to p1.

func NewRadialGradient

func NewRadialGradient(c0 Point, r0 float64, c1 Point, r1 float64, stops ...Stop) *Gradient

NewRadialGradient returns a gradient from the circle (c0, r0) to the circle (c1, r1).

type GradientKind

type GradientKind uint8

GradientKind is linear or radial.

const (
	LinearGradient GradientKind = iota
	RadialGradient
)

The kinds of Gradient.

type Group

type Group uint8

Group orders the layers a Host holds: tiles lie under the active layer, which lies under the overlay, which lies under the HUD.

const (
	GroupTiles Group = iota
	GroupActive
	GroupOverlay
	GroupHUD
)

The groups of layers a Host draws, from the bottom: static tiles, the active layer of dragged nodes, the overlay of sprites, the HUD in view coordinates.

type Hit

type Hit struct {
	Pt   Point
	U    float64
	Dist float64
}

Hit is the result of Nearest: the closest point, its position u (segment index + t, as in Split) and the distance to the query point.

type HitMode

type HitMode uint8

HitMode says what part of a node a hit test accepts.

const (
	HitBounds HitMode = iota // the node's bounds
	HitFill                  // inside the shape
	HitStroke                // within the tolerance of the shape
	HitNone                  // never a hit
)

type Host

type Host interface {
	NewLayer(g Group) Layer
	// Begin and Commit bracket the layer changes of one frame, so that they appear together.
	Begin()
	Commit()
}

Host is the surface the compositor puts layers on: a layer-backed view. All calls come from one goroutine, the one that runs Frame.

type Image

type Image interface{ Size() (w, h float64) }

Image is a raster a backend can draw. *Raster is the portable one; a backend may add its own.

type Item

type Item struct {
	Pic   *Picture
	M     Affine
	Alpha float64
	Clips []Clip
}

Item is one picture to draw: through M, under the clips, composited at Alpha.

func ClipItems

func ClipItems(items []Item, area Rect, bg Color) []Item

ClipItems returns items clipped to area, with a background of the whole area first when bg is not transparent: what a page of a fixed size gets, so that nothing lies outside the area.

type Items

type Items struct {
	List []Item
	// contains filtered or unexported fields
}

Items is a reusable buffer for Collect.

func (*Items) Reset

func (b *Items) Reset()

Reset empties b, keeping its memory.

type Iter

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

Iter decodes a Picture command by command. The zero Iter is ready after Reset; reusing one keeps replays free of allocations.

func (*Iter) Next

func (it *Iter) Next() bool

Next decodes the next command; it reports false at the end of the picture.

func (*Iter) Op

func (it *Iter) Op() *Op

Op returns the command Next decoded.

func (*Iter) Reset

func (it *Iter) Reset(p *Picture)

Reset points the iterator at the start of p.

type Join

type Join uint8

Join is the shape of the corners of a stroked path.

const (
	JoinMiter Join = iota
	JoinRound
	JoinBevel
)

The line joins: sharp (up to MiterLimit), round, or cut off.

type Layer

type Layer interface {
	// SetImage replaces the contents. The Host keeps its own reference; the caller releases img after the call.
	SetImage(img Image)
	// Set places the untransformed frame, then applies m about the point anchor given in the frame's
	// own coordinates.
	Set(frame Rect, anchor Point, m Affine)
	SetOpacity(a float64)
	SetHidden(h bool)
	Remove()
}

Layer is one retained picture a Host composites: a tile, a sprite. Within a group a layer made later lies above one made earlier. Coordinates are view points, y down.

type Measure

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

Measure is a path prepared for arc-length queries.

func (*Measure) At

func (m *Measure) At(s float64) (Point, Point)

At returns the point and unit tangent at arc length s (clamped to 0..Length).

func (*Measure) Length

func (m *Measure) Length() float64

Length returns the length of the flattened path.

type Node

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

Node is one element of the scene tree. Its picture is drawn in the node's own coordinates: the transform maps them into the parent's, and the parent's into the scene's. A clip applies to the node's picture and to the whole subtree. Children draw after their parent, ordered by Z and then by the order they were added; a higher Z draws later and is hit first.

A node changes only through Scene.Update; the getters read the state as of the last Commit and are safe on the goroutine that commits, or inside Scene.Read.

func NewNode

func NewNode(id int) *Node

NewNode returns a detached node. id is the key for Scene.Node; 0 leaves the node unnamed, and with a repeated id Scene.Node returns the last one added.

func (*Node) Bounds

func (n *Node) Bounds() Rect

Bounds is the visible area of the node's own picture in scene coordinates, after the clips of the ancestors; empty when the node has no picture or is clipped away.

func (*Node) Children

func (n *Node) Children() []*Node

Children returns the child nodes in paint order.

func (*Node) Hit

func (n *Node) Hit() HitMode

Hit returns the hit mode.

func (*Node) ID

func (n *Node) ID() int

ID returns the id given to NewNode.

func (*Node) Lifted

func (n *Node) Lifted() bool

Lifted reports whether the node, or an ancestor, is on the active layer.

func (*Node) Opacity

func (n *Node) Opacity() float64

Opacity returns the node's own opacity.

func (*Node) Parent

func (n *Node) Parent() *Node

Parent returns the parent node, the scene root for a top level node.

func (*Node) Picture

func (n *Node) Picture() *Picture

Picture returns the picture of the node, or nil.

func (*Node) Shape

func (n *Node) Shape() *Path

Shape returns the hit shape, or nil.

func (*Node) SubtreeBounds

func (n *Node) SubtreeBounds() Rect

SubtreeBounds is the union of Bounds over the node and everything below it.

func (*Node) Transform

func (n *Node) Transform() Affine

Transform returns the transform to the parent as of the last Commit.

func (*Node) Version

func (n *Node) Version() (self, deep uint32)

Version returns counters that change when the node, or something below it, changes; for caches.

func (*Node) World

func (n *Node) World() Affine

World returns the transform to scene coordinates as of the last Commit.

func (*Node) Z

func (n *Node) Z() int

Z returns the order among siblings.

type Op

type Op struct {
	Kind          OpKind
	A, B, C, D, E float64
	M             Affine
	Color         Color
	Path          *Path
	Style         *StrokeStyle
	Grad          *Gradient
	Shadow        Shadow
	Text          string
	Font          Font
	Image         Image
}

Op is one decoded command. Fields not named by the kind are stale; Path, Style and Grad point into the Iter and are valid until its next Next.

type OpKind

type OpKind uint8

OpKind tells which drawing command an Op is.

const (
	OpSave         OpKind = iota
	OpRestore             //
	OpTranslate           // A, B
	OpScale               // A, B
	OpRotate              // A
	OpTransform           // M
	OpFill                // Path, Color
	OpFillGrad            // Path, Grad
	OpStroke              // Path, Style, Color
	OpStrokeGrad          // Path, Style, Grad
	OpShadowBox           // rounded rect A, B, C, D (x, y, w, h), E radius, Shadow, Color fill
	OpText                // Text, Font, A, B baseline origin, Color
	OpImage               // Image, A, B, C, D destination rect
	OpClipRect            // A, B, C, D
	OpClipRRect           // A, B, C, D, E radius
	OpClipPath            // Path
	OpBeginLayer          // A alpha: everything up to OpEndLayer is composited as one with this alpha
	OpEndLayer            //
	OpFillShadow          // Path, Color fill, Shadow: the shadow of the filled shape, then the shape
	OpStrokeShadow        // Path, Style, Color, Shadow: the shadow of the stroked outline, then the stroke
	OpTextShadow          // as OpText, plus Shadow under the glyphs
)

The operands of each kind are in the fields of Op named after it.

type Options

type Options struct {
	TilePx  int           // tile side in device pixels; 512
	Workers int           // tile rasterizer goroutines; NumCPU-2, at most 6, at least 1
	Margin  int           // tiles kept around the view; 1
	Settle  time.Duration // zoom stands still this long before tiles are redrawn at the new scale; 120 ms
	// ExactZoom draws tiles at exactly the zoom after a gesture instead of the next power of two
	// above it. Sharper at in-between zooms, but no tile is reused when the zoom comes back.
	ExactZoom bool
}

Options tune a Compositor; the zero value gives the defaults noted on each field.

type PDFOptions

type PDFOptions struct {
	// PageW and PageH are the page size in points. Both zero: the page fits the area at Scale
	// plus Margin on every side. Both set: the area is centred in the page inside Margin and
	// scaled to the largest scale that fits, but not past Scale when that is set.
	PageW, PageH float64
	Margin       float64
	// Scale is points per scene unit, or the cap of the fitted scale on a fixed page.
	Scale float64
	// Background, when its A is above zero, is filled over the whole area behind the content.
	Background Color
}

PDFOptions place an area of a scene on a page. The zero value makes a page of the size of the area at one point per scene unit.

func (PDFOptions) Layout

func (o PDFOptions) Layout(area Rect) (PageLayout, error)

Layout computes the layout of area under o, or an error when nothing is left to draw into.

type PDFRenderer

type PDFRenderer interface {
	NewPDF(w io.Writer) (Document, error)
}

PDFRenderer is a Renderer that can also write PDF: CoreGraphics on macOS, cairo on Linux; on Windows the PDF writer of package gfx/pdf with Direct2D's text engine for font lookup.

type Page

type Page interface {
	// Draw paints the items in order, as Target.Draw does: scale is points per scene unit and origin
	// the scene point at the top left corner of the page.
	Draw(scale float64, origin Point, items []Item)
}

Page is drawn in points, y down, the origin at the top left corner. Text stays text and shapes stay vector: nothing is rasterized except what the picture holds (images, shadows on some backends).

type PageLayout

type PageLayout struct {
	W, H   float64 // page size in points
	Scale  float64 // points per scene unit
	Origin Point   // scene point at the top left corner of the page
}

PageLayout says where an area of the scene lies on a page.

type Path

type Path struct {
	Verbs []Verb
	Pts   []Point
	// EvenOdd selects the even-odd fill rule, for fills and clips; the default is non-zero winding.
	EvenOdd bool
}

Path is a list of verbs over a flat point list: MoveTo and LineTo take one point, QuadTo two, CubicTo three, ClosePath none. Arcs and ellipses are stored as cubics.

func EllipsePath

func EllipsePath(r Rect) *Path

EllipsePath returns the ellipse that fits in r.

func ParseSVGPath

func ParseSVGPath(d string) (*Path, error)

ParseSVGPath reads the d attribute of an SVG path into a Path.

func PolygonPath

func PolygonPath(pts ...Point) *Path

PolygonPath returns the closed path through pts, in order.

func RectPath

func RectPath(r Rect) *Path

RectPath returns a closed path around r; it is also the hit shape of a plain box.

func RoundRectPath

func RoundRectPath(r Rect, radius float64) *Path

RoundRectPath returns RectPath with the corners rounded by radius.

func RoundRectPath4

func RoundRectPath4(r Rect, radii [4]float64) *Path

RoundRectPath4 returns RectPath with each corner rounded by its own radius (top left, top right, bottom right, bottom left).

func (*Path) Arc

func (p *Path) Arc(cx, cy, r, a0, a1 float64)

Arc adds a circular arc from angle a0 to a1 (radians, y down: positive is clockwise on screen) as cubics of at most 90 degrees; it joins the current subpath with a line to the arc start.

func (*Path) ArcTo

func (p *Path) ArcTo(x1, y1, x2, y2, r float64)

ArcTo adds the arc of radius r that is tangent to the line from the current point to (x1, y1) and to the line from (x1, y1) to (x2, y2), as the HTML canvas arcTo does: a straight segment to the first tangent point, then the arc to the second. A zero radius, a repeated point or three points on a line give a straight segment to (x1, y1); without a current point the path starts at (x1, y1).

func (*Path) Bounds

func (p *Path) Bounds() Rect

Bounds is the tight bounding box of the drawn geometry: curve extrema come from the roots of the derivative, not from the control points. An empty path gives EmptyRect.

func (*Path) Clone

func (p *Path) Clone() *Path

Clone returns a deep copy.

func (*Path) Close

func (p *Path) Close()

Close ends the subpath with a line back to its start.

func (*Path) Contains

func (p *Path) Contains(q Point, tol float64) bool

Contains reports whether q is inside the filled path under the non-zero winding rule. Curves are flattened with tolerance tol; open subpaths are treated as closed.

func (*Path) CubicTo

func (p *Path) CubicTo(c1x, c1y, c2x, c2y, x, y float64)

CubicTo adds a cubic curve with two control points ending at (x, y).

func (*Path) Ellipse

func (p *Path) Ellipse(cx, cy, rx, ry float64)

Ellipse adds a closed ellipse centred at (cx, cy) as four cubics.

func (*Path) Empty

func (p *Path) Empty() bool

Empty reports whether p has no verbs.

func (*Path) Flatten

func (p *Path) Flatten(tol float64) []Polyline

Flatten converts the path to polylines whose distance to the curves is at most tol.

func (*Path) LineTo

func (p *Path) LineTo(x, y float64)

LineTo adds a straight line to (x, y).

func (*Path) Measure

func (p *Path) Measure(tol float64) *Measure

Measure flattens the path for arc-length queries; the length is the polyline length, so it is slightly short on curves. Gaps between subpaths are not counted.

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float64)

MoveTo starts a new subpath at (x, y).

func (*Path) Nearest

func (p *Path) Nearest(q Point) (Hit, bool)

Nearest finds the point on the path closest to q. The second result is false for a path with no segments.

func (*Path) QuadTo

func (p *Path) QuadTo(cx, cy, x, y float64)

QuadTo adds a quadratic curve with control point (cx, cy) ending at (x, y).

func (*Path) Rect

func (p *Path) Rect(x, y, w, h float64)

Rect adds a closed rectangle.

func (*Path) Reset

func (p *Path) Reset()

Reset removes every verb, keeping the memory.

func (*Path) RoundRect

func (p *Path) RoundRect(x, y, w, h, r float64)

RoundRect adds a rectangle with corner radius r (clamped to half the shorter side).

func (*Path) RoundRect4

func (p *Path) RoundRect4(x, y, w, h float64, r [4]float64)

RoundRect4 adds a rectangle with its own radius at each corner, in the order top left, top right, bottom right, bottom left. Each radius is clamped to half the shorter side.

func (*Path) SVG

func (p *Path) SVG() string

SVG returns p as the d attribute of an SVG path.

func (*Path) Split

func (p *Path) Split(u float64) (a, b *Path)

Split cuts the path at u = segment index + t (t in 0..1; segments count every drawn line or curve, including the line a ClosePath adds). Both halves are open paths; closes become lines.

func (*Path) Transform

func (p *Path) Transform(m Affine) *Path

Transform returns a copy of p with every point mapped by m.

type Picture

type Picture struct {
	Bounds Rect
	// Lod, when set, replaces this picture where its larger side is under LodBelow device pixels.
	// It should look like p at that size; a backend fades it out over the band above LodBelow.
	Lod      *Picture
	LodBelow float64
	// contains filtered or unexported fields
}

Picture is a recorded command list with its bounds in the coordinates it was recorded in. Commands live in one byte stream: a kind byte, then float32 coordinates, 8-bit colors and varint indices. It is immutable after Finish and safe to replay from several goroutines.

func (*Picture) Equal

func (p *Picture) Equal(q *Picture) bool

Equal reports whether q draws exactly what p draws, Lod included. Scene.SetPicture uses it to ignore a picture that did not change, so a node moved with its content is not redrawn.

func (*Picture) Len

func (p *Picture) Len() int

Len is the number of bytes of the command stream.

func (*Picture) Size

func (p *Picture) Size() int

Size is the memory the picture holds, without Lod and images.

func (*Picture) WriteSVG

func (p *Picture) WriteSVG(out io.Writer, scale float64) error

WriteSVG writes p as an SVG document sized to its bounds times scale.

type Point

type Point struct{ X, Y float64 }

Point is a position or a vector in scene units, y down.

func (Point) Add

func (p Point) Add(q Point) Point

Add returns p + q.

func (Point) Dist

func (p Point) Dist(q Point) float64

Dist returns the distance from p to q.

func (Point) Dot

func (p Point) Dot(q Point) float64

Dot returns the dot product of p and q.

func (Point) Len

func (p Point) Len() float64

Len returns the length of p as a vector.

func (Point) Mul

func (p Point) Mul(f float64) Point

Mul returns p scaled by f.

func (Point) Sub

func (p Point) Sub(q Point) Point

Sub returns p - q.

func (Point) Unit

func (p Point) Unit() Point

Unit returns p scaled to length 1, or the zero Point for a zero vector.

type Polyline

type Polyline struct {
	Pts    []Point
	Closed bool
}

Polyline is a flattened subpath.

type Raster

type Raster struct {
	W, H int
	Pix  []byte
}

Raster is a portable image: non-premultiplied RGBA, 4 bytes per pixel, rows top to bottom. Backends convert it on first use and keep the converted copy by the *Raster until the Raster is collected, so a Raster must not change after it was drawn.

func FromBGRA

func FromBGRA(pix []byte, w, h int) *Raster

FromBGRA converts premultiplied BGRA pixels, the layout of the CoreGraphics bitmaps, to a Raster.

func NewRaster

func NewRaster(w, h int) *Raster

NewRaster returns a transparent Raster of w by h pixels.

func RasterFrom

func RasterFrom(img image.Image) *Raster

RasterFrom copies img.

func RenderPicture

func RenderPicture(r Renderer, p *Picture, scale float64, bg Color) (*Raster, error)

RenderPicture draws one picture at the given scale into a Raster of its bounds.

func RenderSubtree

func RenderSubtree(r Renderer, s *Scene, root *Node, area Rect, scale float64, bg Color) (*Raster, error)

RenderSubtree draws the subtree of root, with the clips of its ancestors, into a Raster; a nil root draws the whole scene. area is the scene rectangle to draw, or the zero Rect for the bounds of the subtree; scale is device pixels per scene unit. bg is the background and is transparent when it is the zero Color; use White for an opaque page. It commits the scene's pending transactions first and needs no window.

Example

RenderSubtree draws a node and its subtree into a Raster; offscreen.PNG does the same in one call.

package main

import (
	"fmt"

	"github.com/haiodo/gowt/gfx"
	"github.com/haiodo/gowt/gfx/offscreen"
)

func main() {
	rec := gfx.NewRecorder()
	rec.FillRRect(gfx.R(0, 0, 160, 80), 10, gfx.RGB(30, 120, 220))
	n := gfx.NewNode(1)
	scene := gfx.NewScene()
	scene.Update(func(tx *gfx.Tx) {
		tx.Add(nil, n)
		tx.SetPicture(n, rec.Finish())
	})

	r, err := offscreen.New(offscreen.Options{})
	if err != nil {
		fmt.Println(err)
		return
	}
	// the zero Rect is the bounds of the subtree; 2 is device pixels per scene unit
	raster, err := gfx.RenderSubtree(r, scene, n, gfx.Rect{}, 2, gfx.White)
	if err != nil {
		fmt.Println(err)
		return
	}
	png, _ := raster.PNG()
	fmt.Println(len(png) > 0)
}

func (*Raster) Image

func (r *Raster) Image() *image.NRGBA

Image returns r as an image.NRGBA sharing the pixels.

func (*Raster) PNG

func (r *Raster) PNG() ([]byte, error)

PNG encodes r as a PNG file.

func (*Raster) Size

func (r *Raster) Size() (float64, float64)

Size returns the size in pixels as floats, so a *Raster is an Image.

type Recorder

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

Recorder builds a Picture and tracks its bounds through the transform and clip stack.

Example

The Recorder has a helper for each common shape; Text takes the baseline origin.

package main

import (
	"fmt"

	"github.com/haiodo/gowt/gfx"
)

func main() {
	rec := gfx.NewRecorder()
	rec.FillRect(gfx.R(0, 0, 100, 40), gfx.RGB(240, 240, 245))
	rec.StrokeRRect(gfx.R(0, 0, 100, 40), 6, gfx.StrokeStyle{Width: 2}, gfx.RGB(26, 128, 255))
	rec.FillEllipse(gfx.R(80, 20, 30, 30), gfx.RGBA(230, 51, 51, 0.8))
	pic := rec.Finish()
	fmt.Println(pic.Bounds.W() > 100, pic.Bounds.H() > 40)
}
Output:
true true

func NewRecorder

func NewRecorder() *Recorder

NewRecorder returns a Recorder that measures text with DefaultMeasurer.

func NewRecorderWith

func NewRecorderWith(m TextMeasurer) *Recorder

NewRecorderWith is NewRecorder with m measuring text bounds.

func (*Recorder) BeginLayer

func (r *Recorder) BeginLayer(alpha float64)

BeginLayer starts a group composited as one at the given alpha; end it with EndLayer.

func (*Recorder) ClipPath

func (r *Recorder) ClipPath(p *Path)

ClipPath limits what follows to the inside of p, by its fill rule.

func (*Recorder) ClipRRect

func (r *Recorder) ClipRRect(rc Rect, radius float64)

ClipRRect is ClipRect with corners of the given radius.

func (*Recorder) ClipRect

func (r *Recorder) ClipRect(rc Rect)

ClipRect limits what follows, until the enclosing Restore, to rc.

func (*Recorder) DrawImage

func (r *Recorder) DrawImage(img Image, x, y, w, h float64)

DrawImage draws img stretched into the rectangle at (x, y) of size w by h.

func (*Recorder) EndLayer

func (r *Recorder) EndLayer()

EndLayer closes the group BeginLayer opened and draws it with its alpha.

func (*Recorder) FillEllipse

func (r *Recorder) FillEllipse(rc Rect, c Color)

FillEllipse fills the ellipse that fits in rc.

func (*Recorder) FillGradient

func (r *Recorder) FillGradient(p *Path, g *Gradient)

FillGradient fills p with g.

func (*Recorder) FillPath

func (r *Recorder) FillPath(p *Path, c Color)

FillPath copies p into the picture.

func (*Recorder) FillRRect

func (r *Recorder) FillRRect(rc Rect, radius float64, c Color)

FillRRect fills rc with corners rounded by radius.

func (*Recorder) FillRRect4

func (r *Recorder) FillRRect4(rc Rect, radii [4]float64, c Color)

FillRRect4 fills rc with a radius per corner (top left, top right, bottom right, bottom left).

func (*Recorder) FillRect

func (r *Recorder) FillRect(rc Rect, c Color)

FillRect fills rc.

func (*Recorder) FillShadowPath

func (r *Recorder) FillShadowPath(p *Path, c Color, sh Shadow)

FillShadowPath fills p with a blurred drop shadow of its shape under it. The offset of the shadow is in the coordinates of p, so it turns and mirrors with the transform.

func (*Recorder) FillShadowRRect

func (r *Recorder) FillShadowRRect(x, y, w, h, radius float64, fill Color, sh Shadow)

FillShadowRRect fills a rounded rectangle with a blurred drop shadow under it.

func (*Recorder) Finish

func (r *Recorder) Finish() *Picture

Finish returns the picture; the Recorder must not be used afterwards.

func (*Recorder) Restore

func (r *Recorder) Restore()

Restore pops what Save pushed.

func (*Recorder) Rotate

func (r *Recorder) Rotate(a float64)

Rotate rotates what follows by a radians about the origin.

func (*Recorder) Save

func (r *Recorder) Save()

Save pushes the transform and the clip.

func (*Recorder) Scale

func (r *Recorder) Scale(x, y float64)

Scale scales what follows by x and y about the origin.

func (*Recorder) StrokeEllipse

func (r *Recorder) StrokeEllipse(rc Rect, st StrokeStyle, c Color)

StrokeEllipse strokes the outline of the ellipse that fits in rc.

func (*Recorder) StrokeGradient

func (r *Recorder) StrokeGradient(p *Path, st StrokeStyle, g *Gradient)

StrokeGradient strokes p with st, painted by g.

func (*Recorder) StrokePath

func (r *Recorder) StrokePath(p *Path, st StrokeStyle, c Color)

StrokePath strokes p with st in color c.

func (*Recorder) StrokeRRect

func (r *Recorder) StrokeRRect(rc Rect, radius float64, st StrokeStyle, c Color)

StrokeRRect strokes the outline of rc with corners rounded by radius.

func (*Recorder) StrokeRRect4

func (r *Recorder) StrokeRRect4(rc Rect, radii [4]float64, st StrokeStyle, c Color)

StrokeRRect4 strokes the outline of rc with a radius per corner (top left, top right, bottom right, bottom left).

func (*Recorder) StrokeRect

func (r *Recorder) StrokeRect(rc Rect, st StrokeStyle, c Color)

StrokeRect strokes the outline of rc, centred on its edge.

func (*Recorder) StrokeShadowPath

func (r *Recorder) StrokeShadowPath(p *Path, st StrokeStyle, c Color, sh Shadow)

StrokeShadowPath strokes p with a blurred drop shadow of the stroke under it.

func (*Recorder) Text

func (r *Recorder) Text(s string, x, y float64, f Font, c Color)

Text draws s with its baseline origin at (x, y); the bounds come from the recorder's measurer.

func (*Recorder) TextShadow

func (r *Recorder) TextShadow(s string, x, y float64, f Font, c Color, sh Shadow)

TextShadow is Text with a blurred drop shadow of the glyphs under it.

func (*Recorder) Transform

func (r *Recorder) Transform(m Affine)

Transform multiplies the current transform by m: m applies first.

func (*Recorder) Translate

func (r *Recorder) Translate(x, y float64)

Translate moves the origin of what follows by (x, y).

type Rect

type Rect struct{ Min, Max Point }

Rect is an axis-aligned rectangle. Use EmptyRect as the identity of Union.

func EmptyRect

func EmptyRect() Rect

EmptyRect returns the rectangle that contains nothing: the identity of Union.

func R

func R(x, y, w, h float64) Rect

R returns the rectangle with top left (x, y) and size w by h.

func (Rect) AddPoint

func (r Rect) AddPoint(p Point) Rect

AddPoint returns r grown to hold p.

func (Rect) Center

func (r Rect) Center() Point

Center returns the middle of r.

func (Rect) Contains

func (r Rect) Contains(p Point) bool

Contains reports whether p lies inside r or on its edge.

func (Rect) Empty

func (r Rect) Empty() bool

Empty reports whether r contains no area.

func (Rect) Expand

func (r Rect) Expand(d float64) Rect

Expand returns r grown by d on every side; a negative d shrinks it.

func (Rect) H

func (r Rect) H() float64

H returns the height of r.

func (Rect) Intersect

func (r Rect) Intersect(o Rect) Rect

Intersect returns the common area; the result is Empty when there is none.

func (Rect) Intersects

func (r Rect) Intersects(o Rect) bool

Intersects reports whether r and o overlap.

func (Rect) Translate

func (r Rect) Translate(d Point) Rect

Translate returns r moved by d.

func (Rect) Union

func (r Rect) Union(o Rect) Rect

Union returns the smallest rectangle that holds r and o.

func (Rect) W

func (r Rect) W() float64

W returns the width of r.

type Renderer

type Renderer interface {
	TextMeasurer
	NewTarget(wpx, hpx int) Target
}

Renderer is a drawing backend: CoreGraphics on macOS. It is safe for concurrent use, its Targets are not shared.

type SVGOptions

type SVGOptions struct {
	// Background, when its A is above zero, is filled over the whole area behind the content.
	Background Color
}

SVGOptions are the extras of WriteSubtreeSVGWith. The zero value is WriteSubtreeSVG.

type Scene

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

Scene is a tree of nodes with a uniform grid over the visible bounds of their pictures. Changes are made in transactions with Update and applied by Commit, which the frame loop calls; queries may run concurrently with each other and with Update.

func NewScene

func NewScene() *Scene

NewScene returns an empty scene. It has no bounds: nodes may lie anywhere.

func (*Scene) Collect

func (s *Scene) Collect(r Rect, b *Items)

Collect fills b with what is drawn inside r, in paint order, leaving out lifted nodes. The items are valid until the next Collect into b, and need no lock to draw.

func (*Scene) CollectSubtree

func (s *Scene) CollectSubtree(root *Node, r Rect, b *Items)

CollectSubtree is Collect for root and its descendants only, lifted or not.

func (*Scene) Commit

func (s *Scene) Commit() []Rect

Commit applies the queued transactions in order and returns the scene areas whose pixels changed: the old and the new bounds of every node that moved or changed, lifted nodes aside. A window's frame loop calls it. Without one (a test, a program that renders to PNG) call it after Update before reading nodes or hit-testing: until then HitTest, Query and the getters of Node still show the scene as it was. RenderSubtree and offscreen.PNG commit by themselves.

func (*Scene) HitTest

func (s *Scene) HitTest(p Point, tol float64) *Node

HitTest returns the topmost node under the scene point p, or nil. tol is the stroke tolerance and the bounds slack in scene units (screen pixels divided by the zoom). Clips of the ancestors count. It sees the scene as of the last Commit.

func (*Scene) Len

func (s *Scene) Len() int

Len is the number of nodes in the scene, the root excluded.

func (*Scene) Node

func (s *Scene) Node(id int) *Node

Node returns the node with the given ID, or nil.

func (*Scene) Pending

func (s *Scene) Pending() bool

Pending reports whether a transaction waits for Commit.

func (*Scene) Query

func (s *Scene) Query(r Rect, dst []*Node) []*Node

Query appends the nodes whose visible bounds meet r to dst in paint order.

func (*Scene) Read

func (s *Scene) Read(f func())

Read runs f holding the read lock, so that the getters of nodes are safe on any goroutine.

func (*Scene) Root

func (s *Scene) Root() *Node

Root is the node every top level node hangs under; it has no picture.

func (*Scene) Update

func (s *Scene) Update(f func(tx *Tx))

Update runs f to record a transaction and queues it; Commit applies it whole, so a frame shows either all of it or none. It is safe from any goroutine, and f runs before Update returns.

type ScreenScaler

type ScreenScaler interface{ SetScreenScale(devicePerPoint float64) }

ScreenScaler is implemented by the Targets of the backends that draw Shadow.Screen: it sets how many device pixels one screen point of such a shadow is. The Compositor sets the display's backing scale before every tile; a Target that was not told uses 1.

type Shadow

type Shadow struct {
	DX, DY, Blur float64
	Color        Color
	Screen       bool
}

Shadow is a blurred drop shadow offset by (DX, DY).

With Screen set, DX, DY and Blur are in screen points instead: the backend applies them at rasterization, in the axes of the screen and ignoring the node and camera scale, so a shadow keeps its size while the view zooms (CoreGraphics setShadow does the same). A screen point is the backing scale of the display (Compositor.SetViewport dpr), or one device pixel for a target that was not told (see ScreenScaler). The shadow does not turn with a rotated node.

type Space

type Space uint8

Space says how a Sprite's position and picture relate to the camera.

const (
	// SpaceScene: the picture is in scene units and zooms with the scene; Pos is a scene point.
	SpaceScene Space = iota
	// SpacePinned: Pos is a scene point, the picture is in points and keeps its size: handles, labels.
	SpacePinned
	// SpaceScreen: Pos is a view point, the picture is in points.
	SpaceScreen
)

type Sprite

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

Sprite is a picture on the compositor's overlay, moved by the compositor alone: it is drawn once and then only placed, so a cursor flying over a busy scene costs no redrawing. The picture's origin (0, 0) lies at Pos. Its methods are safe from any goroutine; they take effect on the next Frame, and animations count their time from it.

func (*Sprite) FadeTo

func (s *Sprite) FadeTo(a float64, d time.Duration, ease Easing, done func())

FadeTo animates the opacity to a over d. done, when not nil, runs on the frame that finishes it.

func (*Sprite) FlyAlong

func (s *Sprite) FlyAlong(path *Path, d time.Duration, ease Easing, orient bool, done func())

FlyAlong moves the sprite along path (in the coordinates of Pos) over d. Easing shapes the progress along the arc length. With orient, the sprite is rotated to the path direction.

Example

Animations run on the frame clock of the compositor; set a goal once from any goroutine.

package main

import (
	"time"

	"github.com/haiodo/gowt/gfx"
)

func main() {
	var comp *gfx.Compositor // from view.View.Compositor()
	rec := gfx.NewRecorder()
	rec.FillEllipse(gfx.R(0, 0, 10, 10), gfx.RGB(230, 51, 51))
	cursor := comp.NewSprite(rec.Finish(), gfx.SpacePinned, gfx.Point{})
	path := &gfx.Path{}
	path.MoveTo(0, 0)
	path.CubicTo(60, 0, 100, 80, 200, 120)
	cursor.FlyAlong(path, 600*time.Millisecond, gfx.EaseInOut, false, nil)
}

func (*Sprite) MoveTo

func (s *Sprite) MoveTo(p Point, d time.Duration, ease Easing, done func())

MoveTo glides to p over d along ease; done, if set, runs on the Frame goroutine when it arrives.

func (*Sprite) Pos

func (s *Sprite) Pos() Point

Pos is the position as of the last Frame.

func (*Sprite) Remove

func (s *Sprite) Remove()

Remove takes the sprite off the overlay.

func (*Sprite) RotateTo

func (s *Sprite) RotateTo(rad float64, d time.Duration, ease Easing, done func())

RotateTo animates the angle to rad over d.

func (*Sprite) ScaleTo

func (s *Sprite) ScaleTo(f float64, d time.Duration, ease Easing, done func())

ScaleTo animates the scale to f over d.

func (*Sprite) SetOpacity

func (s *Sprite) SetOpacity(a float64)

SetOpacity sets the opacity at once and stops a fade under way.

func (*Sprite) SetPicture

func (s *Sprite) SetPicture(p *Picture)

SetPicture replaces what the sprite shows; it is drawn again once.

func (*Sprite) SetPos

func (s *Sprite) SetPos(p Point)

SetPos puts the sprite at p at once and stops any move or flight under way.

func (*Sprite) SetRotation

func (s *Sprite) SetRotation(rad float64)

SetRotation sets the angle in radians at once and stops a rotation under way.

func (*Sprite) SetScale

func (s *Sprite) SetScale(f float64)

SetScale sets the scale at once and stops a scaling under way.

type Stats

type Stats struct {
	FrameTime    time.Duration // CPU time of the last Frame
	TilesApplied int           // tile images put on layers by the last Frame
	TilesPending int           // tiles queued or being drawn
	Rastered     uint64        // tiles drawn since the start
	RasterTime   time.Duration // total worker time spent drawing tiles
	SpriteDraws  int           // sprites drawn by the last Frame on the calling goroutine
	HUDDraws     int           // times the HUD image was drawn by the last Frame
}

Stats counts what the compositor did; Frame fills the per-frame fields.

type Stop

type Stop struct {
	Offset float64
	Color  Color
}

Stop is a color at Offset 0..1 along a gradient.

type StrokeStyle

type StrokeStyle struct {
	Width      float64
	Cap        Cap
	Join       Join
	MiterLimit float64
	Dash       []float64
	DashPhase  float64
}

StrokeStyle describes a stroke. The zero value is a hairline with butt caps and miter joins; set Width.

type Target

type Target interface {
	// Begin clears the target to bg and maps the scene point origin to the top left pixel
	// at scale device pixels per scene unit.
	Begin(scale float64, origin Point, bg Color)
	// Draw paints the items in order.
	Draw(items []Item)
	Size() (wpx, hpx int)
	// Pixels is premultiplied BGRA, rows top to bottom; valid until Close.
	Pixels() []byte
	// Snapshot returns the current pixels as an Image of the given size in points, for a Host.
	Snapshot(wpt, hpt float64) Image
	Close()
}

Target is an offscreen bitmap a Renderer draws into. One Target is used by one goroutine at a time.

type TextMeasurer

type TextMeasurer interface {
	MeasureText(s string, f Font) TextMetrics
}

TextMeasurer reports the size of text as the backend draws it.

var DefaultMeasurer TextMeasurer = EstimateText{}

DefaultMeasurer is what NewRecorder uses. Importing a backend (gfx/cg, gfx/cairo, gfx/d2d, and so gfx/view and gfx/offscreen) replaces it with that backend's measurer, so text bounds match what is drawn whatever the order of recording and of creating a renderer. Without a backend it is EstimateText.

func LazyMeasurer

func LazyMeasurer(open func() (TextMeasurer, error)) TextMeasurer

LazyMeasurer returns a TextMeasurer that calls open on its first use, once, and measures with the result; when open fails it estimates with EstimateText. Backends use it so that a renderer is made only if text is recorded.

type TextMetrics

type TextMetrics struct{ Width, Ascent, Descent float64 }

TextMetrics are the extents of a laid-out line in points; Ascent and Descent are positive.

type Tx

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

Tx records changes to a scene. It is valid only inside the Update call that made it.

Example

A node can move, fade and be clipped without touching its picture.

package main

import (
	"fmt"

	"github.com/haiodo/gowt/gfx"
)

func main() {
	scene := gfx.NewScene()
	frame, item := gfx.NewNode(1), gfx.NewNode(2)
	rec := gfx.NewRecorder()
	rec.FillRect(gfx.R(0, 0, 50, 50), gfx.Black)
	scene.Update(func(tx *gfx.Tx) {
		tx.Add(nil, frame)
		tx.Add(frame, item) // children move with their parent
		tx.SetPicture(item, rec.Finish())
		tx.ClipRRect(frame, gfx.R(0, 0, 30, 30), 4) // clips the frame and its subtree
		tx.Move(frame, 10, 10)
	})
	scene.Commit()
	fmt.Println(item.Bounds())
}
Output:
{{10 10} {40 40}}

func (*Tx) Add

func (tx *Tx) Add(parent, n *Node)

Add attaches n, with its subtree, under parent; a nil parent means the root.

func (*Tx) ClipPath

func (tx *Tx) ClipPath(n *Node, p *Path)

ClipPath keeps p by reference.

func (*Tx) ClipRRect

func (tx *Tx) ClipRRect(n *Node, r Rect, radius float64)

ClipRRect clips n and its subtree to a rounded rectangle in the coordinates of n.

func (*Tx) ClipRRect4

func (tx *Tx) ClipRRect4(n *Node, r Rect, radii [4]float64)

ClipRRect4 is ClipRRect with a radius per corner (top left, top right, bottom right, bottom left).

func (*Tx) ClipRect

func (tx *Tx) ClipRect(n *Node, r Rect)

ClipRect clips n and its subtree to r (in n's coordinates).

func (*Tx) Move

func (tx *Tx) Move(n *Node, x, y float64)

Move sets the translation of n, keeping the rest of its transform.

func (*Tx) NoClip

func (tx *Tx) NoClip(n *Node)

NoClip removes the clip of n.

func (*Tx) Remove

func (tx *Tx) Remove(n *Node)

Remove detaches n with its subtree and forgets the IDs.

func (*Tx) Reparent

func (tx *Tx) Reparent(n, parent *Node)

Reparent moves n under another parent, keeping its own transform.

func (*Tx) SetOpacity

func (tx *Tx) SetOpacity(n *Node, v float64)

SetOpacity sets the opacity of n, 0 to 1; it multiplies down the subtree.

func (*Tx) SetPicture

func (tx *Tx) SetPicture(n *Node, pic *Picture)

SetPicture sets what n draws, in its own coordinates. A picture equal to the current one changes nothing.

func (*Tx) SetShape

func (tx *Tx) SetShape(n *Node, shape *Path, hit HitMode)

SetShape sets the geometry hit-testing uses (local coordinates, kept by reference) and how.

func (*Tx) SetTransform

func (tx *Tx) SetTransform(n *Node, m Affine)

SetTransform sets the transform of n relative to its parent.

func (*Tx) SetZ

func (tx *Tx) SetZ(n *Node, z int)

SetZ sets the order of n among its siblings; a higher Z draws later and is hit first.

type Verb

type Verb uint8

Verb is one drawing step of a Path.

const (
	MoveTo Verb = iota
	LineTo
	QuadTo
	CubicTo
	ClosePath
)

The verbs of a Path.

Directories

Path Synopsis
Package cairo replays gfx Pictures with cairo and Pango into image surfaces on Linux, without a window, a display or GTK: only libcairo, libpango, libpangocairo, libgobject and fontconfig are loaded, with purego.
Package cairo replays gfx Pictures with cairo and Pango into image surfaces on Linux, without a window, a display or GTK: only libcairo, libpango, libpangocairo, libgobject and fontconfig are loaded, with purego.
Package cg replays gfx Pictures with CoreGraphics and CoreText into CGBitmapContext surfaces on macOS, without creating any window.
Package cg replays gfx Pictures with CoreGraphics and CoreText into CGBitmapContext surfaces on macOS, without creating any window.
Package d2d replays gfx Pictures with Direct2D 1.1 and DirectWrite on Windows, with no window: the device is a D3D11 WARP device, so no GPU is needed and a service, CI or an SSH session in session 0 can render.
Package d2d replays gfx Pictures with Direct2D 1.1 and DirectWrite on Windows, with no window: the device is a D3D11 WARP device, so no GPU is needed and a service, CI or an SSH session in session 0 can render.
internal
cache
Package cache holds the caches the gfx backends keep per Renderer, bounded so that a scene which keeps making new strings, shadows or Rasters does not grow them without end.
Package cache holds the caches the gfx backends keep per Renderer, bounded so that a scene which keeps making new strings, shadows or Rasters does not grow them without end.
fonttest
Package fonttest holds the font checks every gfx backend must pass, so that cg, cairo and d2d are held to the same behavior.
Package fonttest holds the font checks every gfx backend must pass, so that cg, cairo and d2d are held to the same behavior.
pdftest
Package pdftest holds the PDF checks every gfx backend must pass, so that cg, cairo and the Windows writer are held to the same behavior.
Package pdftest holds the PDF checks every gfx backend must pass, so that cg, cairo and the Windows writer are held to the same behavior.
Package layout is a flexbox-like auto-layout for editors and design tools: rows and columns with gap, padding, alignment, justification, wrapping, min and max sizes, absolute children, and fixed, hug and fill sizes.
Package layout is a flexbox-like auto-layout for editors and design tools: rows and columns with gap, padding, alignment, justification, wrapping, min and max sizes, absolute children, and fixed, hug and fill sizes.
Package offscreen renders a gfx scene to an image without a window, a display or a build tag: it picks the headless gfx.Renderer of the running OS (CoreGraphics on macOS, cairo and Pango on Linux, Direct2D on Windows).
Package offscreen renders a gfx scene to an image without a window, a display or a build tag: it picks the headless gfx.Renderer of the running OS (CoreGraphics on macOS, cairo and Pango on Linux, Direct2D on Windows).
Package pdf writes gfx pictures as PDF without any system library: paths, strokes, gradients, clips, images, group opacity and text.
Package pdf writes gfx pictures as PDF without any system library: paths, strokes, gradients, clips, images, group opacity and text.
Package pen loads pen.dev design files (.pen, JSON) into gfx scene subtrees.
Package pen loads pen.dev design files (.pen, JSON) into gfx scene subtrees.
Package printing draws gfx pictures and scenes onto the pages of a gowt.PrintJob.
Package printing draws gfx pictures and scenes onto the pages of a gowt.PrintJob.
Package synth builds a synthetic UI-mockup / diagram document for gfx benchmarks: rounded boxes with border, shadow and two text lines, joined by cubic connectors with arrowheads, every third one dashed.
Package synth builds a synthetic UI-mockup / diagram document for gfx benchmarks: rounded boxes with border, shadow and two text lines, joined by cubic connectors with arrowheads, every third one dashed.
Package view puts a gfx scene into a gowt window as a widget.
Package view puts a gfx scene into a gowt window as a widget.

Jump to

Keyboard shortcuts

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