graphics

package
v0.5.52 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 32 Imported by: ? modules, 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 graphics is the meui drawing seam: meui-owned value types, a Paint, and a Canvas facade. Toolkit packages depend on this package rather than on the renderer that backs it, so a second backend can be supplied without touching widget code.

Neutral-type migration (P1) is in progress. Color, Point, Rect, Size, Matrix and Paint are meui-owned here. Path and Image are still aliases to the mobilegles types and become owned interfaces when the Canvas facade is split over a Device (P1b-3); until then the conversions below are how the seam talks to the renderer.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoOffscreen = errors.New("graphics: offscreen rendering unavailable")

Device is the complete backend contract the seam draws through. A Device owns the surface, the transform/clip state stack and every draw operation; Canvas is a thin facade over one, so the toolkit never names a backend.

This is P1's L1 seam (design §5.2). It is deliberately shaped around what the toolkit actually calls rather than around any one renderer: the used surface is ~25 operations, which is what makes a second backend feasible. ErrNoOffscreen reports that no backend is installed or that it cannot render to an offscreen surface.

View Source
var MonospacedFont = SystemFont

MonospacedFont falls back to SystemFont; core has no monospace distinction.

Functions

func BlurHorizontal added in v0.5.5

func BlurHorizontal(pix []uint32, w, h int)

Renderer adapters that need the same blur kernel as the software device use these wrappers; the seam keeps the implementation private.

func BlurVertical added in v0.5.5

func BlurVertical(pix []uint32, w, h int)

func CaptureOffscreen

func CaptureOffscreen(dev Device, width, height int, draw func(*Canvas), done func(*image.NRGBA))

CaptureOffscreen renders draw into an offscreen surface on dev and hands the pixels to done as a composited NRGBA image. A nil device or a backend that cannot render offscreen simply produces nothing, matching the previous behaviour when the renderer had no context.

func MaskRoundedCorners added in v0.5.5

func MaskRoundedCorners(pix []uint32, w, h int, radius float32)

func NeedsShaping added in v0.5.19

func NeedsShaping(text string) bool

NeedsShaping reports whether text contains a non-ASCII rune. The default gate keeps Latin metrics on the existing path while complex scripts use the shaped engine; MEUI_SHAPED_TEXT=1 forces shaping for every string.

func NewSoftDevice

func NewSoftDevice(w, h int) *softDevice

NewSoftDevice returns a software device of the given size. The pixels are white-transparent until something clears them.

func RegisterDeviceFactory added in v0.5.5

func RegisterDeviceFactory(f func(width, height float32) Device)

RegisterDeviceFactory installs the process-wide renderer-backed Device. A backend calls this once during initialization.

func RegisterFontFamily

func RegisterFontFamily(family, path string, w weight.Enum, sl slant.Enum) error

RegisterFontFamily parses a TTF and registers it under family at a weight and slant. An empty family uses the font's own name table. OTF is not accepted: the parser this tree uses cannot read it (that is a separate gap, recorded in WEB.md).

func RegisteredFamilies

func RegisteredFamilies() []string

RegisteredFamilies lists the app-supplied families, sorted.

func RenderShapedText added in v0.5.21

func RenderShapedText(text string, f Font, col uint32) (*image.RGBA, bool)

RenderShapedText rasterizes a shaped line into a transparent RGBA image. It is the shared bridge for backends that present text as a texture (SDL GPU) instead of drawing glyph quads. Coordinates are pen-relative, with the baseline at y=em.

func SetShapedTextSupport added in v0.5.19

func SetShapedTextSupport(on bool)

SetShapedTextSupport enables the default shaped path for backends that can draw glyph IDs. It is additive with MEUI_SHAPED_TEXT=1; a backend without glyph-run rendering leaves it false so layout and drawing stay rune-based.

func ShapedTextEnabled added in v0.5.19

func ShapedTextEnabled() bool

ShapedTextEnabled reports whether shaped layout/drawing is active.

func ShouldShapeText added in v0.5.19

func ShouldShapeText(text string) bool

ShouldShapeText is the default draw/layout decision for a string.

func WeightEnum

func WeightEnum(w int) weight.Enum

WeightEnum maps a CSS-style numeric weight (100..900) to the face-weight enum. It is the ONE mapping: the QML `font.weight` handler and the theme presets both call it, so a 600 cannot mean "semibold" in a scene and "bold" in a preset.

Types

type BackdropBlurrer

type BackdropBlurrer interface {
	BlurBackdrop(r Rect, cornerRadius float32) bool
}

BackdropBlurrer is implemented by devices that can blur what they have already painted — the frosted-glass operation. The GL device does it through its blur FBO, the software device with the same 7-tap kernel (see softdevice_blur.go).

type BlendMode

type BlendMode int

BlendMode selects how a draw composites with what is already there.

const (
	BlendModeNormal BlendMode = iota
	BlendModeMultiply
	BlendModeScreen
	BlendModeOverlay
	BlendModeDarken
	BlendModeLighten
	BlendModeColorDodge
	BlendModeColorBurn
	BlendModeHardLight
	BlendModeSoftLight
	BlendModeDifference
	BlendModeExclusion
	BlendModeHue
	BlendModeSaturation
	BlendModeColor
	BlendModeLuminosity
)

type Canvas

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

Canvas is the drawing facade the toolkit paints through. It holds a Device and owns no backend state of its own, so swapping the Device swaps the renderer without touching a single widget call site.

func NewCanvas

func NewCanvas(dev Device) *Canvas

NewCanvas wraps a Device in the seam facade.

func NewSoftwareCanvas

func NewSoftwareCanvas(w, h int) (*Canvas, *softDevice)

NewSoftwareCanvas returns a Canvas drawing into a fresh software surface of the given size, plus the device so the caller can take its pixels. Callers use it to rasterise a widget on the CPU - the same draw code, a different canvas.

func (*Canvas) BlurBackdrop

func (c *Canvas) BlurBackdrop(r Rect, cornerRadius float32) bool

BlurBackdrop blurs the painted surface inside r and composites it back, masked to a rounded rect of cornerRadius (0 is a plain rectangle). It reports false when the device has no blur path, so a widget can fall back to a plain translucent fill instead of drawing nothing.

func (*Canvas) Clear

func (c *Canvas) Clear(col uint32)

func (*Canvas) ClearWithViewport

func (c *Canvas) ClearWithViewport(col uint32, x, y, w, h int32)

func (*Canvas) ClipBounds

func (c *Canvas) ClipBounds() Rect

ClipBounds is the clip in force, in device space.

func (*Canvas) ClipDepth

func (c *Canvas) ClipDepth() int

func (*Canvas) ClipPath

func (c *Canvas) ClipPath(path *Path) bool

ClipPath intersects the clip with the interior of path, transformed by the current matrix like every other local-space draw call. Exact for convex outlines; a concave outline clips to its bounding rectangle (a superset) and returns false.

func (*Canvas) ClipRect

func (c *Canvas) ClipRect(rect Rect, _ pathop.Enum, _ bool)

func (*Canvas) Device

func (c *Canvas) Device() Device

Device returns the backend this canvas draws through (may be nil).

func (*Canvas) DrawArc

func (c *Canvas) DrawArc(rect Rect, start, sweep float32, paint *Paint)

DrawArc: meui signature (rect Rect, start, sweep float32, paint *Paint).

func (*Canvas) DrawCircle

func (c *Canvas) DrawCircle(cx, cy, r float32, paint *Paint)

DrawCircle: meui signature (cx, cy, r float32, paint *Paint).

func (*Canvas) DrawDashedLine

func (c *Canvas) DrawDashedLine(x1, y1, x2, y2 float32, dash []float32, phase float32, paint *Paint)

DrawDashedLine: meui signature (x1, y1, x2, y2, dash, phase, paint).

func (*Canvas) DrawImageInRect

func (c *Canvas) DrawImageInRect(img *Image, rect Rect, _ *Image, paint *Paint)

DrawImageInRect accepts the meui (img, rect, sampling, paint) signature. sampling is ignored.

func (*Canvas) DrawImageRectInRect

func (c *Canvas) DrawImageRectInRect(img *Image, _, dst Rect, _ *Image, paint *Paint)

DrawImageRectInRect: approximation, ignores srcRect and sampling.

func (*Canvas) DrawLine

func (c *Canvas) DrawLine(x1, y1, x2, y2 float32, paint *Paint)

DrawLine: meui signature (x1, y1, x2, y2 float32, paint *Paint).

func (*Canvas) DrawOval

func (c *Canvas) DrawOval(rect Rect, paint *Paint)

DrawOval: meui signature (rect Rect, paint *Paint).

func (*Canvas) DrawPath

func (c *Canvas) DrawPath(path *Path, paint *Paint)

func (*Canvas) DrawRect

func (c *Canvas) DrawRect(rect Rect, paint *Paint)

DrawRect: meui signature (rect Rect, paint *Paint).

func (*Canvas) DrawRoundedRect

func (c *Canvas) DrawRoundedRect(rect Rect, rx, ry float32, paint *Paint)

DrawRoundedRect: meui signature (rect Rect, rx, ry float32, paint *Paint).

func (*Canvas) DrawSimpleString

func (c *Canvas) DrawSimpleString(s string, x, y float32, font Font, paint *Paint)

DrawSimpleString: meui signature (s string, x, y float32, font Font, paint *Paint).

func (*Canvas) DrawText

func (c *Canvas) DrawText(text string, x, y float32, font Font, p *Paint)

DrawText: meui signature (s string, x, y float32, font Font, paint *Paint).

func (*Canvas) DropShadow

func (c *Canvas) DropShadow(rect Rect, paint *Paint, offsetX, offsetY, radius float32)

DropShadow: meui signature (rect Rect, paint *Paint, offsetX, offsetY, radius float32).

func (*Canvas) Height

func (c *Canvas) Height() float32

func (*Canvas) IsClipEmpty

func (c *Canvas) IsClipEmpty() bool

IsClipEmpty reports a clip that admits nothing — which is NOT the same as a clip covering the whole surface, and is what a widget checks before drawing at all.

func (*Canvas) Origin

func (c *Canvas) Origin() (float32, float32)

Origin returns the current canvas translation (matrix tx, ty).

func (*Canvas) QuickRejectRect

func (c *Canvas) QuickRejectRect(r Rect) bool

QuickRejectRect reports whether a rect lies entirely outside the clip, so a widget drawing many items can skip the ones that cannot be seen. It is a conservative test: false only means "not provably invisible".

func (*Canvas) ResetClip

func (c *Canvas) ResetClip()

func (*Canvas) Restore

func (c *Canvas) Restore()

func (*Canvas) RestoreToCount

func (c *Canvas) RestoreToCount(n int)

func (*Canvas) Rotate

func (c *Canvas) Rotate(degrees float32)

func (*Canvas) Save

func (c *Canvas) Save()

func (*Canvas) SaveAndRestore

func (c *Canvas) SaveAndRestore(fn func())

func (*Canvas) Scale

func (c *Canvas) Scale(x, y float32)

func (*Canvas) Skew

func (c *Canvas) Skew(kx, ky float32)

func (*Canvas) Translate

func (c *Canvas) Translate(x, y float32)

func (*Canvas) Width

func (c *Canvas) Width() float32

Width and Height report the device surface size.

func (*Canvas) WithClip

func (c *Canvas) WithClip(rect Rect, fn func(*Canvas))

ClipRect: meui passes (rect, pathop, antialias). The rect is in the canvas's LOCAL (user) space, exactly like every other draw call, so it is transformed by the current matrix before becoming a device clip. (The shim previously mistook the antialias flag for a "local" toggle and skipped the transform, clipping widgets at their untranslated positions.) WithClip draws with a clip and restores the previous one, whatever fn does.

It is the transaction form of ClipRect, and it exists because the manual form leaks: the historic TextField bug was a paint that pushed a clip and never popped it, poisoning everything painted after it in that frame. A defer cannot be forgotten, so prefer this to Save/ClipRect/Restore.

type Color

type Color uint32

Color is a meui-owned 0xAARRGGBB colour. It is deliberately kept as a scalar with the same encoding: the toolkit uses raw colour literals throughout and compares them to untyped constants.

func ARGB

func ARGB(alpha float32, red, green, blue int) Color

ARGB matches the reference signature: alpha as a 0.0–1.0 float and red/green/blue as 0–255 ints. mobilegles has only uint8 RGBA, so scale alpha to 0–255 and clamp.

func ColorDecode

func ColorDecode(s string) (Color, error)

ColorDecode parses CSS-style color strings: hex (#RGB, #RRGGBB), rgb(r,g,b), rgba(r,g,b,a), or named colors. This is a partial implementation of the reference ColorDecode.

func RGB

func RGB(r, g, b uint8) Color

RGB creates an opaque colour.

func RGBA

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

RGBA creates a colour with an explicit alpha.

func (Color) Paint

func (c Color) Paint(_ *Canvas, _ Rect, _ int32) *Paint

Paint satisfies Ink so a plain colour can be used wherever ink is asked for (TextDecoration.OnBackgroundInk). This mirrors mobilegles.Color's own Paint method.

type Device

type Device interface {
	// Surface
	Width() float32
	Height() float32
	Clear(col uint32)
	ClearWithViewport(col uint32, x, y, w, h int32)

	// Transform and clip state
	Save() int
	Restore()
	RestoreToCount(n int)
	Translate(dx, dy float32)
	Scale(sx, sy float32)
	Rotate(deg float32)
	Skew(kx, ky float32)
	GetMatrix() Matrix
	TransformRect(x, y, w, h float32) (float32, float32, float32, float32)
	ClipRect(r Rect)
	// ClipPath intersects the clip with the interior of path. It reports
	// whether the clip is exact: a concave or over-complex outline falls back
	// to its bounding rectangle (a superset, so nothing is hidden) and returns
	// false.
	ClipPath(path *Path) bool
	ResetClip()
	ClipDepth() int
	// ClipBounds is the clip in force, in device space. A widget that draws many
	// items uses it with QuickRejectRect to skip what cannot be seen.
	ClipBounds() Rect
	// IsClipEmpty reports a clip that admits nothing, which is different from a
	// clip that happens to be the whole surface.
	IsClipEmpty() bool
	// QuickRejectRect reports whether a rect lies entirely outside the clip.
	QuickRejectRect(r Rect) bool

	// Drawing
	DrawRect(x, y, w, h float32, p *Paint)
	DrawRoundedRect(r Rect, rx, ry float32, p *Paint)
	DrawCircle(cx, cy, r float32, p *Paint)
	DrawOval(x, y, w, h float32, p *Paint)
	DrawArc(x, y, w, h, start, sweep float32, p *Paint)
	DrawLine(x1, y1, x2, y2 float32, p *Paint)
	DrawDashedLine(x1, y1, x2, y2 float32, dash []float32, phase float32, p *Paint)
	DrawPath(path *Path, p *Paint)
	DrawImage(img *Image, r Rect, p *Paint)
	DrawText(text string, x, y float32, f Font, p *Paint)
	DrawSimpleString(text string, x, y float32, f Font, p *Paint)
	DropShadow(r Rect, p *Paint, dx, dy, radius float32)

	// RenderOffscreen draws into a separate surface and returns it. Widget
	// caches and screenshot paths use this, so the backend owns offscreen
	// creation instead of the seam reaching for a renderer.
	RenderOffscreen(width, height int, draw func(*Canvas)) (*Image, error)
}

func NewDevice added in v0.5.5

func NewDevice(width, height float32) Device

NewDevice creates the installed backend device, or nil if no backend has registered one (headless tests, a scene that never paints).

type Font

type Font = *FontImpl

Font is an alias for *FontImpl. It is shaped as a pointer so a zero value of Font is a nil pointer (matching the reference Font interface zero-value semantics) and `Font: nil` works in struct literals.

var SystemFont Font = wrapSystemFont()

SystemFont is pre-allocated to a Font wrapping the resolved system face. It may be nil if no system font is loaded.

func ReloadSystemFont

func ReloadSystemFont() Font

ReloadSystemFont re-resolves SystemFont (and MonospacedFont) from the platform's CURRENT system font.

SystemFont is resolved once, at package init, and a widget captures the face it was built with — so installing a font later changed the underlying face without changing anything an app could see. That made LoadFontFace, which is documented as the way to ship your own UI font, silently ineffective: text already laid out kept the old glyphs and the theme kept pointing at them, with no error anywhere.

Changing a font at runtime needs both halves: this re-resolves the font, and theme.UseSystemFont makes the theme use it. Neither package can do the other's half, because theme imports graphics and not the reverse.

type FontDescriptor

type FontDescriptor struct {
	Family  string
	Weight  weight.Enum
	Spacing spacing.Enum
	Slant   slant.Enum
	Size    float32
	Face    *truetype.Font // concrete face; nil = resolve by family
}

FontDescriptor describes a font by family, weight, spacing, slant, and size. Calling .Font() produces a Font at the given size, with the requested weight/spacing/slant baked in.

func (*FontDescriptor) Font

func (fd *FontDescriptor) Font() Font

Font returns a Font of the given size based on this descriptor.

type FontFace

type FontFace struct {
	Weight  weight.Enum
	Spacing spacing.Enum
	Slant   slant.Enum

	// Synthetic styles for faces without real bold/italic companions
	// (rasterized emboldened/sheared — Skia-style synthesis).
	SyntheticBold   bool
	SyntheticItalic bool
	// contains filtered or unexported fields
}

FontFace is our own FontFace type. It carries a descriptor; calling Font(size) produces a Font at the given size. Family is exposed via the Family() method, not a field, to match the reference FontFace API. face, when non-nil, is the concrete truetype font the family resolved to (embedded Roboto faces); nil means "use the system font".

func LoadFontFace

func LoadFontFace(path string) (*FontFace, error)

LoadFontFace loads a truetype/otf font from path and returns a FontFace for it — lets applications ship their own UI fonts (e.g. fonts/InterDisplay-Regular.otf) instead of falling through the system-font candidate list.

func MatchFontFace

func MatchFontFace(family string, w weight.Enum, sp spacing.Enum, sl slant.Enum) *FontFace

MatchFontFace resolves a family/style to a concrete font face. Reference parity: only the embedded Roboto family resolves (the reference embeds Roboto and, unlike skia's font manager here, we do not fall back to arbitrary system fonts); unknown families return nil so callers fall back exactly like production.

func (*FontFace) Face

func (ff *FontFace) Face() *FontFace

Face returns this descriptor as a *FontFace. Used in code that iterates over `[]FontFaceDescriptor` and rebuilds fonts at a new size: `for _, fd := range all { f := fd.Face().Font(size) }`.

func (*FontFace) Family

func (ff *FontFace) Family() string

Family returns the family name. Method form (mirrors the reference FontFace.Family()).

func (*FontFace) Font

func (ff *FontFace) Font(size float32) Font

Font returns a Font of the given size based on this descriptor.

func (*FontFace) Style

func (ff *FontFace) Style() (weight.Enum, spacing.Enum, slant.Enum)

Style returns the (weight, spacing, slant) triple. Method form (mirrors the reference FontFace.Style()).

type FontFaceDescriptor

type FontFaceDescriptor = FontFace

FontFaceDescriptor is a placeholder for compatibility.

func AllFontFaces

func AllFontFaces() (all, monospaced []FontFaceDescriptor)

type FontImpl

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

FontImpl is our own Font type. It holds font metadata and the parsed face; a renderer adapter builds its glyph engine from Descriptor/RasterSize.

func (*FontImpl) Baseline

func (f *FontImpl) Baseline() float32

func (*FontImpl) Descriptor

func (f *FontImpl) Descriptor() FontDescriptor

func (*FontImpl) Face

func (f *FontImpl) Face() *FontFace

Face returns a FontFace descriptor for this font. Used to re-create the font at a different size. Carries the resolved truetype face so re-created fonts rasterize with the same family (reference parity — dropping it silently swapped the family for the system font).

func (*FontImpl) Family

func (f *FontImpl) Family() string

func (*FontImpl) Font

func (f *FontImpl) Font() *truetype.Font

Font returns the underlying *truetype.Font. Matches the reference Font interface signature so meui code that does `meuishim.MonospacedFont.Font.Face()` works as if it were the truetype face. nil if no truetype face is available.

func (*FontImpl) FontFace

func (f *FontImpl) FontFace() *FontFace

FontFace returns a descriptor for this font. Used for re-creating the font at a different size.

func (*FontImpl) ForText added in v0.5.24

func (f *FontImpl) ForText(text string) Font

ForText returns a Font that can draw every rune in text. The primary face is used when it covers the string; otherwise the discovered system face is tried as a whole-string fallback. Per-script face fallback would need a font map, but this removes the tofu boxes a single-script font produced for mixed text.

func (*FontImpl) LineHeight

func (f *FontImpl) LineHeight() float32

func (*FontImpl) PositionedGlyphs added in v0.5.19

func (f *FontImpl) PositionedGlyphs(text string) ([]PositionedGlyph, float32, bool)

PositionedGlyphs lays a single line out in visual slots. It is the bridge software and GPU renderers use so they all walk the same bidi order.

func (*FontImpl) RasterSize added in v0.5.5

func (f *FontImpl) RasterSize() float32

RasterSize is the fitted em size the renderer uses to build its glyph atlas. It is exported for backend adapters; widgets use Size/Baseline.

func (*FontImpl) ShapedCaretX added in v0.5.16

func (f *FontImpl) ShapedCaretX(text string, byteOffset int) (float32, bool)

ShapedCaretX returns the x offset of the caret before byteOffset in text. Mixed-direction runs are placed with the UAX #9 L2 visual order, so this is not limited to all-LTR or all-RTL lines.

func (*FontImpl) ShapedIndexAtX added in v0.5.16

func (f *FontImpl) ShapedIndexAtX(text string, x float32) (int, bool)

ShapedIndexAtX is the inverse of ShapedCaretX: the byte offset whose caret is nearest x.

func (*FontImpl) ShapedText added in v0.5.10

func (f *FontImpl) ShapedText(text string) ([]textshape.Run, error)

ShapedText shapes text with the canonical textshape engine at this font's em size. The result is for measurement/selection and the future glyph-ID draw path; renderers still draw runes until TEXT-3 is wired.

func (*FontImpl) ShapedTextDir added in v0.5.10

func (f *FontImpl) ShapedTextDir(text string, dir textshape.Direction) ([]textshape.Run, error)

ShapedTextDir is ShapedText with an explicit paragraph direction.

func (*FontImpl) ShapedWidth added in v0.5.14

func (f *FontImpl) ShapedWidth(text string) (float32, bool)

ShapedWidth returns the widest shaped line, or false when the font has no retained source. It is the measurement half of the shaped draw path, so enabling MEUI_SHAPED_TEXT keeps label sizing and glyph placement agreeing.

func (*FontImpl) SimpleWidth

func (f *FontImpl) SimpleWidth(text string) float32

SimpleWidth is an alias for TextWidth.

func (*FontImpl) Size

func (f *FontImpl) Size() float32

func (*FontImpl) Source added in v0.5.13

func (f *FontImpl) Source() []byte

Source returns the raw TTF this face was parsed from, when the loader retained it. It is for shaping bridges; callers must not modify it.

func (*FontImpl) Synthetic

func (f *FontImpl) Synthetic() (bold, italic bool)

Synthetic reports whether the face lacks real bold/italic and the atlas synthesizes them (raster embolden/shear).

func (*FontImpl) TextWidth

func (f *FontImpl) TextWidth(text string) float32

func (*FontImpl) TruetypeFace

func (f *FontImpl) TruetypeFace() *truetype.Font

TruetypeFace returns the underlying truetype font face, or nil.

type Gradient

type Gradient struct {
	Kind  GradientKind
	Stops []GradientStop
	Start Point
	End   Point
	// Center/Radius serve GradientRadial and GradientConic; Radius is unused by
	// the conic form, which uses StartAngle.
	Center     Point
	Radius     float32
	StartAngle float32
}

Gradient is a meui-owned multi-stop gradient. Exactly one geometry applies, chosen by Kind:

GradientLinear: the ramp runs from Start to End.
GradientRadial: the ramp runs from Center out to Radius.
GradientConic:  the ramp sweeps around Center from StartAngle degrees.

type GradientKind

type GradientKind int

GradientKind selects a gradient's geometry.

const (
	GradientNone GradientKind = iota
	GradientLinear
	GradientRadial
	GradientConic
)

type GradientStop

type GradientStop struct {
	Offset float32
	Color  Color
}

GradientStop is one colour stop at Offset (0..1) along the gradient.

type Image

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

Image is meui-owned: it holds the pixel buffer and dimensions, and the backend image is built from it on demand. A Device therefore never has to be handed a renderer object by the caller.

func NewImage

func NewImage(rgba []uint32, w, h int32) *Image

NewImage wraps a bottom-up 0xAARRGGBB pixel buffer.

func NewImageFromBytes

func NewImageFromBytes(data []byte) (*Image, error)

NewImageFromBytes decodes PNG, JPEG or GIF bytes into an image.

The result is premultiplied, which is the seam's image convention: an Image is handed to the backend as premultiplied pixels (offscreen readbacks already are, and decoded straight-alpha data is premultiplied here so both kinds composite identically).

func NewImageFromDrawing

func NewImageFromDrawing(dev Device, width, height, ppi int, draw func(*Canvas)) (*Image, error)

NewImageFromDrawing renders draw into an offscreen surface belonging to dev and returns the result. The backend owns offscreen creation, so the seam never reaches for a renderer itself.

func NewImageFromFilePathOrURL

func NewImageFromFilePathOrURL(filePathOrURL string, scale float32) (*Image, error)

NewImageFromFilePathOrURL loads an image from a filesystem path.

Remote URLs are deliberately NOT fetched: the drawing seam performs no network I/O. Fetch the bytes with whatever HTTP client the app already uses and pass them to NewImageFromBytes.

scale resamples the decoded image (bilinear); 0 and 1 mean "as decoded".

func NewImageFromRGBA

func NewImageFromRGBA(rgba []byte, w, h int) (*Image, error)

The display path for a rendered buffer: sRGB-encoded RGBA8 in, a graphics.Image out.

It exists because the two sides disagree about three things at once, and every caller getting all three right by hand is not a reasonable thing to ask:

  • Alpha: the 8-bit world (PNG, JPEG, a document's display buffer) carries STRAIGHT alpha, and the seam's word is PREMULTIPLIED, so each pixel is premultiplied exactly once here.
  • Order: the seam stores pixels BOTTOM-UP, like the GL readbacks the renderer already feeds it, while a decoded or rendered buffer arrives TOP-DOWN, so the rows are flipped on the way in.
  • Packing: the seam's word is 0xAARRGGBB.

Getting any one of them wrong produces a picture that looks plausible — a subtly dark image, an upside-down one, or red and blue swapped — which is exactly why this is one function rather than a paragraph of instructions.

func (*Image) Bounds

func (i *Image) Bounds() Rect

Bounds reports the image extent as a Rect with its origin at (0, 0).

func (*Image) Height

func (i *Image) Height() int32

func (*Image) LogicalSize

func (i *Image) LogicalSize() Size

LogicalSize returns the dimensions as a seam Size, for layout.

func (*Image) PixelAt

func (i *Image) PixelAt(x, y int) Color

PixelAt returns the pixel at (x, y), in TOP-LEFT image coordinates, with straight alpha (the inverse of the premultiplication SetPixel applies). Out-of-range reads return a fully transparent colour.

func (*Image) Pixels

func (i *Image) Pixels() []uint32

Pixels returns the raw buffer (bottom-up 0xAARRGGBB, premultiplied).

func (*Image) PutImage

func (i *Image) PutImage(src *Image, dx, dy int)

PutImage copies src over the receiver with its top-left corner at (dx, dy) — the canvas putImageData operation. Both images are premultiplied, so the copy is a straight blit; the parts of src that fall outside the receiver are dropped and the backend texture is marked stale.

func (*Image) Scaled

func (i *Image) Scaled(scale float32) *Image

Scaled returns a bilinear resample of the image. A scale of 0 or 1 returns the receiver unchanged. Interpolating premultiplied pixels is the correct way to resample alpha-carrying content.

func (*Image) SetPixel

func (i *Image) SetPixel(x, y int, c Color)

SetPixel writes c at (x, y), given in TOP-LEFT image coordinates, and marks the backend texture stale so the next draw re-uploads it. c is straight alpha and is premultiplied here; writes outside the image are ignored.

func (*Image) SetPixels

func (i *Image) SetPixels(pix []uint32)

SetPixels replaces the image's pixel buffer in place, for a buffer that is re-rendered on the same surface (a cached layer). The dimensions must match: the backend keeps one texture per image, and swapping a different-sized buffer under it would re-upload at the wrong extent. The next draw re-uploads.

func (*Image) ToPNG

func (i *Image) ToPNG(compressionLevel int) ([]byte, error)

ToPNG encodes the image through the backend.

func (*Image) Width

func (i *Image) Width() int32

type Ink

type Ink interface {
	Paint(canvas *Canvas, rect Rect, style int32) *Paint
}

Ink is anything that can produce a Paint for a rect. It is meui-owned — no backend type appears in the signature. Color satisfies it, which is what TextDecoration.OnBackgroundInk is normally set to.

type Matrix

type Matrix [9]float32 // row-major 3x3 affine: [sx, kx, tx, ky, sy, ty, 0, 0, 1]

func NewMatrix

func NewMatrix() Matrix

type Paint

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

Paint is a meui-owned draw state. Its fields stay unexported and are read/written through methods, matching the call sites the toolkit already uses; the renderer's own paint is built lazily behind it.

func NewPaint

func NewPaint() *Paint

NewPaint returns a paint with the same defaults the renderer uses: opaque white, filled, 1px stroke, butt caps, miter joins (limit 4), antialiased, fully opaque, normal blend.

func (*Paint) Antialias

func (p *Paint) Antialias() bool

func (*Paint) BlendMode

func (p *Paint) BlendMode() BlendMode

func (*Paint) ClearGradient

func (p *Paint) ClearGradient()

func (*Paint) Color

func (p *Paint) Color() Color

func (*Paint) GlobalAlpha

func (p *Paint) GlobalAlpha() float32

func (*Paint) Gradient

func (p *Paint) Gradient() Gradient

Gradient returns the paint's gradient; Kind == GradientNone means solid.

func (*Paint) MiterLimit

func (p *Paint) MiterLimit() float32

func (*Paint) SetAntialias

func (p *Paint) SetAntialias(on bool)

SetAntialias turns edge antialiasing on or off for this paint. Text and images are unaffected: they sample a texture and have no edge ramp.

func (*Paint) SetBlendMode

func (p *Paint) SetBlendMode(m BlendMode)

func (*Paint) SetColor

func (p *Paint) SetColor(c Color)

func (*Paint) SetConicGradient

func (p *Paint) SetConicGradient(center Point, startAngle float32, stops []GradientStop)

SetConicGradient sets a multi-stop gradient sweeping around center from startAngle degrees.

func (*Paint) SetGlobalAlpha

func (p *Paint) SetGlobalAlpha(a float32)

SetGlobalAlpha multiplies the alpha of everything this paint draws, on top of the colour's own alpha. Values outside 0..1 are clamped; 1 is no modulation. Unlike SetAntialias this applies to text and images too.

func (*Paint) SetGradient

func (p *Paint) SetGradient(g Gradient)

SetGradient replaces the paint's gradient wholesale.

func (*Paint) SetLinearGradient

func (p *Paint) SetLinearGradient(start, end Point, stops []GradientStop)

SetLinearGradient sets a multi-stop gradient running start→end.

func (*Paint) SetMiterLimit

func (p *Paint) SetMiterLimit(limit float32)

SetMiterLimit sets how far a miter join may spike, in multiples of half the stroke width, before it is beveled. Values <= 0 restore the default of 4.

func (*Paint) SetRadialGradient

func (p *Paint) SetRadialGradient(center Point, radius float32, stops []GradientStop)

SetRadialGradient sets a multi-stop gradient running from center out to radius.

func (*Paint) SetStrokeCap

func (p *Paint) SetStrokeCap(c StrokeCap)

func (*Paint) SetStrokeJoin

func (p *Paint) SetStrokeJoin(j StrokeJoin)

func (*Paint) SetStrokeWidth

func (p *Paint) SetStrokeWidth(w float32)

func (*Paint) SetStyle

func (p *Paint) SetStyle(style int32)

func (*Paint) StrokeCap

func (p *Paint) StrokeCap() StrokeCap

func (*Paint) StrokeJoin

func (p *Paint) StrokeJoin() StrokeJoin

func (*Paint) StrokeWidth

func (p *Paint) StrokeWidth() float32

func (*Paint) Style

func (p *Paint) Style() int32

type Path

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

func NewPath

func NewPath() *Path

func (*Path) Close

func (p *Path) Close()

func (*Path) CubicTo

func (p *Path) CubicTo(ctrl1, ctrl2, end Point)

CubicTo adds a cubic bezier segment from the current point through the two controls to end. A Device flattens it into whatever its rasterizer supports.

func (*Path) LineTo

func (p *Path) LineTo(pt Point)

func (*Path) MoveTo

func (p *Path) MoveTo(pt Point)

func (*Path) Ops

func (p *Path) Ops() []PathOp

Ops returns the recorded operations. A Device implementation replays these into its own path type.

func (*Path) QuadTo

func (p *Path) QuadTo(ctrl, end Point)

func (*Path) Reset

func (p *Path) Reset()

type PathOp

type PathOp struct {
	Kind   PathOpKind
	P0, P1 Point
	P2     Point
}

PathOp is one recorded path operation. P0 is the control point for PathQuadTo and the target for the others; for PathQuadTo P1 is the end point, and for PathCubicTo P0/P1 are the two controls and P2 the end.

type PathOpKind

type PathOpKind uint8

Path is meui-owned pure data: it records the ops the caller issues, and a Device replays them into whatever path representation the backend uses. No renderer type is involved, which is what lets a second backend render paths.

const (
	PathMoveTo PathOpKind = iota
	PathLineTo
	PathQuadTo
	PathCubicTo
	PathClose
)

type Point

type Point struct{ X, Y float32 }

Point, Rect, Size and Matrix are plain meui-owned value types. The toolkit only ever reads their fields, so they carry no geometry methods.

func NewPoint

func NewPoint(x, y float32) Point

type PositionedGlyph added in v0.5.19

type PositionedGlyph struct {
	Glyph textshape.Glyph
	X     float32
	Y     float32
}

PositionedGlyph is one shaped glyph at a pen-relative x offset. Y is the shaping offset from the baseline; callers add the baseline themselves.

type Rect

type Rect struct{ X, Y, Width, Height float32 }

func NewRect

func NewRect(x, y, w, h float32) Rect

func (Rect) Contains

func (r Rect) Contains(x, y float32) bool

Contains reports whether the point (x, y) lies inside the rectangle.

func (Rect) Intersects

func (r Rect) Intersects(other Rect) bool

Intersects reports whether the rectangles overlap. Kept on the owned type because the toolkit uses it (debug tree layout).

type Size

type Size struct{ Width, Height float32 }

func NewSize

func NewSize(w, h float32) Size

type StrokeCap

type StrokeCap int

StrokeCap is the line-end style for stroked draws.

const (
	StrokeCapButt StrokeCap = iota
	StrokeCapRound
	StrokeCapSquare
)

type StrokeJoin

type StrokeJoin int

StrokeJoin is the line-join style for stroked draws.

const (
	StrokeJoinMiter StrokeJoin = iota
	StrokeJoinRound
	StrokeJoinBevel
)

type SystemFontInfo

type SystemFontInfo struct {
	Family string // family name from the font's name table
	Path   string // font file to load with LoadFontFace
}

SystemFontInfo describes one discovered outline font family.

func ListSystemFonts

func ListSystemFonts(extraDirs ...string) []SystemFontInfo

ListSystemFonts scans the standard font directories (plus any extra dirs, e.g. an app's bundled fonts/) and returns one entry per family. When several faces share a family the "Regular" file wins. Family names come from each font's name table; unparseable files are skipped. The result is scanned once and cached — the first call reads every font file, so call it before the UI is shown.

type TestDevice

type TestDevice struct {

	// Calls counts operations by name.
	Calls map[string]int
	// Total is the number of recorded operations.
	Total int

	// LastText and LastRect capture the most recent text/rect arguments, and
	// LastBlend/LastMiterLimit/LastAntialias the paint state of the most recent
	// stroke, so a test can prove the paint reaches the device rather than
	// being stored and ignored.
	LastText        string
	LastRect        Rect
	LastBlend       BlendMode
	LastMiterLimit  float32
	LastAntialias   bool
	LastGlobalAlpha float32
	// LastClipPathOps is the op count of the most recent ClipPath, so a test can
	// prove the path reached the device.
	LastClipPathOps int
	// contains filtered or unexported fields
}

TestDevice is a recording, drawing-free Device. It covers the seam with a second backend: every operation is counted and the transform/clip stack is emulated so a Canvas over it behaves plausibly. Widget tests paint through it, which proves the toolkit cannot depend on renderer behaviour.

func NewTestDevice

func NewTestDevice(width, height float32) *TestDevice

NewTestDevice returns a recording Device with the given surface size.

func (*TestDevice) Clear

func (d *TestDevice) Clear(col uint32)

func (*TestDevice) ClearWithViewport

func (d *TestDevice) ClearWithViewport(col uint32, x, y, w, h int32)

func (*TestDevice) ClipBounds

func (d *TestDevice) ClipBounds() Rect

func (*TestDevice) ClipDepth

func (d *TestDevice) ClipDepth() int

func (*TestDevice) ClipPath

func (d *TestDevice) ClipPath(path *Path) bool

func (*TestDevice) ClipRect

func (d *TestDevice) ClipRect(r Rect)

func (*TestDevice) Count

func (d *TestDevice) Count(op string) int

Count returns how many times an operation was recorded.

func (*TestDevice) DrawArc

func (d *TestDevice) DrawArc(x, y, w, h, start, sweep float32, p *Paint)

func (*TestDevice) DrawCircle

func (d *TestDevice) DrawCircle(cx, cy, r float32, p *Paint)

func (*TestDevice) DrawDashedLine

func (d *TestDevice) DrawDashedLine(x1, y1, x2, y2 float32, dash []float32, phase float32, p *Paint)

func (*TestDevice) DrawImage

func (d *TestDevice) DrawImage(img *Image, r Rect, p *Paint)

func (*TestDevice) DrawLine

func (d *TestDevice) DrawLine(x1, y1, x2, y2 float32, p *Paint)

func (*TestDevice) DrawOval

func (d *TestDevice) DrawOval(x, y, w, h float32, p *Paint)

func (*TestDevice) DrawPath

func (d *TestDevice) DrawPath(path *Path, p *Paint)

func (*TestDevice) DrawRect

func (d *TestDevice) DrawRect(x, y, w, h float32, p *Paint)

func (*TestDevice) DrawRoundedRect

func (d *TestDevice) DrawRoundedRect(r Rect, rx, ry float32, p *Paint)

func (*TestDevice) DrawSimpleString

func (d *TestDevice) DrawSimpleString(text string, x, y float32, f Font, p *Paint)

func (*TestDevice) DrawText

func (d *TestDevice) DrawText(text string, x, y float32, f Font, p *Paint)

func (*TestDevice) DropShadow

func (d *TestDevice) DropShadow(r Rect, p *Paint, dx, dy, radius float32)

func (*TestDevice) GetMatrix

func (d *TestDevice) GetMatrix() Matrix

func (*TestDevice) Height

func (d *TestDevice) Height() float32

func (*TestDevice) IsClipEmpty

func (d *TestDevice) IsClipEmpty() bool

func (*TestDevice) QuickRejectRect

func (d *TestDevice) QuickRejectRect(r Rect) bool

func (*TestDevice) RenderOffscreen

func (d *TestDevice) RenderOffscreen(width, height int, draw func(*Canvas)) (*Image, error)

RenderOffscreen runs draw against a fresh recording device so widgets still exercise their offscreen path, but reports failure: a drawing-free device cannot produce pixels. Callers already treat that as "no cache image".

func (*TestDevice) ResetClip

func (d *TestDevice) ResetClip()

func (*TestDevice) Restore

func (d *TestDevice) Restore()

func (*TestDevice) RestoreToCount

func (d *TestDevice) RestoreToCount(n int)

func (*TestDevice) Rotate

func (d *TestDevice) Rotate(deg float32)

func (*TestDevice) Save

func (d *TestDevice) Save() int

func (*TestDevice) Scale

func (d *TestDevice) Scale(sx, sy float32)

func (*TestDevice) Skew

func (d *TestDevice) Skew(kx, ky float32)

func (*TestDevice) TransformRect

func (d *TestDevice) TransformRect(x, y, w, h float32) (float32, float32, float32, float32)

TransformRect maps the rect's corners through the current matrix and returns their bounding box, matching what a device clip needs.

func (*TestDevice) Translate

func (d *TestDevice) Translate(dx, dy float32)

func (*TestDevice) Width

func (d *TestDevice) Width() float32

type Text

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

Text is a stub matching the reference Text API surface used by meui. A faithful implementation needs shaping, layout, and per-glyph metrics that mobilegles does not expose. Until then, Text.Draw forwards to Canvas.DrawText with the decoration's font.

func NewText

func NewText(str string, decoration *TextDecoration) *Text

func (*Text) AddString

func (t *Text) AddString(s string, dec *TextDecoration)

AddString appends a string with the given decoration. Stub: the meui code that uses it (markdown rendering) ignores the result for now.

func (*Text) Draw

func (t *Text) Draw(canvas *Canvas, x, y float32)

func (*Text) Width

func (t *Text) Width() float32

Width returns the rendered width of the text through the unified text engine (same walk DrawText uses).

type TextDecoration

type TextDecoration struct {
	Font            Font
	OnBackgroundInk Ink
	StrikeThrough   bool
}

Directories

Path Synopsis
enums
paintstyle
Package paintstyle mirrors the reference toolkit's paint-style enum.
Package paintstyle mirrors the reference toolkit's paint-style enum.
pathop
Package pathop mirrors the reference toolkit's path-op enum.
Package pathop mirrors the reference toolkit's path-op enum.
slant
Package slant mirrors the reference toolkit's slant enum.
Package slant mirrors the reference toolkit's slant enum.
spacing
Package spacing mirrors the reference toolkit's spacing enum.
Package spacing mirrors the reference toolkit's spacing enum.
weight
Package weight mirrors the reference toolkit's weight enum.
Package weight mirrors the reference toolkit's weight enum.
Package textshape provides the pure-Go shaping foundation for MeUI.
Package textshape provides the pure-Go shaping foundation for MeUI.

Jump to

Keyboard shortcuts

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