graphics
Package graphics provides low-level graphics primitives for drawing.
This package defines the fundamental types for rendering user interfaces: geometry (Size, Offset, Rect), colors, gradients, paints, and the Canvas interface for executing drawing operations.
Geometry
Basic geometric types for layout and positioning:
size := graphics.Size{Width: 100, Height: 50}
offset := graphics.Offset{X: 10, Y: 20}
rect := graphics.RectFromLTWH(0, 0, 100, 50)
Colors
Colors are stored as ARGB (0xAARRGGBB):
red := graphics.RGB(255, 0, 0) // Opaque red
semiTransparent := graphics.RGBA(0, 0, 0, 0.5) // 50% black
Drawing
The Canvas interface provides drawing operations:
canvas.DrawRect(rect, paint)
canvas.DrawRRect(rrect, paint)
canvas.DrawText(layout, offset)
Paint controls how shapes are filled or stroked:
paint := graphics.DefaultPaint()
paint.Color = graphics.ColorBlue
paint.Style = graphics.PaintStyleStroke
paint.StrokeWidth = 2
Constants
const (
ColorTransparent = Color(0x00000000)
ColorBlack = Color(0xFF000000)
ColorWhite = Color(0xFFFFFFFF)
ColorRed = Color(0xFFFF0000)
ColorGreen = Color(0xFF00FF00)
ColorBlue = Color(0xFF0000FF)
)
Variables
Named alignment constants for common positions.
var (
// AlignTopLeft positions at the top-left corner (-1, -1).
AlignTopLeft = Alignment{-1, -1}
// AlignTopCenter positions at the top center (0, -1).
AlignTopCenter = Alignment{0, -1}
// AlignTopRight positions at the top-right corner (1, -1).
AlignTopRight = Alignment{1, -1}
// AlignCenterLeft positions at the center-left edge (-1, 0).
AlignCenterLeft = Alignment{-1, 0}
// AlignCenter positions at the center (0, 0).
AlignCenter = Alignment{0, 0}
// AlignCenterRight positions at the center-right edge (1, 0).
AlignCenterRight = Alignment{1, 0}
// AlignBottomLeft positions at the bottom-left corner (-1, 1).
AlignBottomLeft = Alignment{-1, 1}
// AlignBottomCenter positions at the bottom center (0, 1).
AlignBottomCenter = Alignment{0, 1}
// AlignBottomRight positions at the bottom-right corner (1, 1).
AlignBottomRight = Alignment{1, 1}
)
func ResolveRadius
func ResolveRadius(relativeRadius float64, bounds Rect) float64
ResolveRadius converts a relative radius value to absolute pixels. The radius is relative to half the minimum dimension of the bounds, so a radius of 1.0 will touch the nearest edge from the center.
Example:
bounds := graphics.RectFromLTWH(0, 0, 200, 100)
r := graphics.ResolveRadius(1.0, bounds)
// r = 50 (half of the min dimension 100)
func SVGDebugCheckDestroy
func SVGDebugCheckDestroy(ptr unsafe.Pointer)
type Alignment
Alignment represents a position within a rectangle using a coordinate system where the center is (0, 0), with X and Y values typically ranging from -1 to 1.
Coordinate System
The coordinate system maps positions within a bounding rectangle:
(-1,-1) (0,-1) (1,-1)
+-----------+-----------+
| TopLeft | TopCenter | TopRight
| | |
(-1,0) (0,0) (1,0)
+-----------+-----------+
|CenterLeft | Center | CenterRight
| | |
(-1,1) (0,1) (1,1)
+-----------+-----------+
|BottomLeft |BottomCenter| BottomRight
Extending Beyond Bounds
Values outside the -1 to 1 range extend beyond the widget boundaries:
Alignment{-2, 0} // One full width to the left of the widget
Alignment{1.5, 0} // Halfway past the right edge
This is useful for creating gradient overflow effects like glows when combined with Overflow: OverflowVisible.
Usage with Gradients
Alignment is used for gradient positioning, allowing gradients to be defined relative to widget dimensions rather than absolute pixel coordinates:
// Horizontal gradient from left to right edge
graphics.NewLinearGradient(
graphics.AlignCenterLeft,
graphics.AlignCenterRight,
stops,
)
// Diagonal gradient from top-left to bottom-right
graphics.NewLinearGradient(
graphics.AlignTopLeft,
graphics.AlignBottomRight,
stops,
)
// Radial gradient centered in widget
graphics.NewRadialGradient(
graphics.AlignCenter,
1.0, // radius = 100% of half the min dimension
stops,
)
type Alignment struct {
// X is the horizontal position, where -1 is the left edge, 0 is the center,
// and 1 is the right edge. Values outside this range extend beyond the bounds.
X float64
// Y is the vertical position, where -1 is the top edge, 0 is the center,
// and 1 is the bottom edge. Values outside this range extend beyond the bounds.
Y float64
}
func (Alignment) Resolve
func (a Alignment) Resolve(bounds Rect) Offset
Resolve converts the relative alignment to absolute pixel coordinates within the given bounding rectangle.
The conversion uses center-relative coordinates:
X = centerX + alignment.X * (width / 2)
Y = centerY + alignment.Y * (height / 2)
Example:
bounds := graphics.RectFromLTWH(0, 0, 200, 100)
pos := graphics.AlignCenterRight.Resolve(bounds)
// pos = Offset{X: 200, Y: 50}
type BlendMode
BlendMode controls how source and destination colors are composited. Values match Skia's SkBlendMode enum exactly (required for C interop).
type BlendMode int
const (
BlendModeClear BlendMode = iota // clear
BlendModeSrc // src
BlendModeDst // dst
BlendModeSrcOver // src_over
BlendModeDstOver // dst_over
BlendModeSrcIn // src_in
BlendModeDstIn // dst_in
BlendModeSrcOut // src_out
BlendModeDstOut // dst_out
BlendModeSrcATop // src_atop
BlendModeDstATop // dst_atop
BlendModeXor // xor
BlendModePlus // plus
BlendModeModulate // modulate
BlendModeScreen // screen
BlendModeOverlay // overlay
BlendModeDarken // darken
BlendModeLighten // lighten
BlendModeColorDodge // color_dodge
BlendModeColorBurn // color_burn
BlendModeHardLight // hard_light
BlendModeSoftLight // soft_light
BlendModeDifference // difference
BlendModeExclusion // exclusion
BlendModeMultiply // multiply
BlendModeHue // hue
BlendModeSaturation // saturation
BlendModeColor // color
BlendModeLuminosity // luminosity
)
func (BlendMode) String
func (b BlendMode) String() string
String returns a human-readable representation of the blend mode.
type BlurStyle
BlurStyle controls how the blur mask is generated.
type BlurStyle int
const (
// BlurStyleOuter draws nothing inside, blurs outside only.
BlurStyleOuter BlurStyle = iota
// BlurStyleNormal blurs inside and outside the shape.
BlurStyleNormal
// BlurStyleSolid keeps the shape solid inside, blurs outside.
BlurStyleSolid
// BlurStyleInner blurs inside the shape only, nothing outside.
BlurStyleInner
)
func (BlurStyle) String
func (s BlurStyle) String() string
String returns a human-readable representation of the blur style.
type BoxShadow
BoxShadow defines a shadow to draw around a shape.
BlurStyle controls where the shadow appears relative to the shape.
Spread controls the shadow's extent relative to the shape: - Outer/Normal/Solid: positive spread expands the shadow outward. - Inner: positive spread moves the inner edge inward, thickening the band.
BlurRadius controls softness. Sigma for Skia is BlurRadius * 0.5.
type BoxShadow struct {
Color Color
Offset Offset
BlurRadius float64 // sigma = blurRadius * 0.5
Spread float64
BlurStyle BlurStyle
}
func BoxShadowElevation
func BoxShadowElevation(level int, color Color) *BoxShadow
BoxShadowElevation returns a Material-style elevation shadow. Level should be 1-5, where higher levels have larger blur and offset.
func NewBoxShadow
func NewBoxShadow(color Color, blurRadius float64) *BoxShadow
NewBoxShadow creates a simple drop shadow with the given color and blur radius. Offset defaults to (0, 2) for a subtle downward shadow.
func (BoxShadow) Sigma
func (s BoxShadow) Sigma() float64
Sigma returns the blur sigma for Skia's mask filter. Returns 0 if BlurRadius is negative.
type Canvas
Canvas records or renders drawing commands.
type Canvas interface {
// Save pushes the current transform and clip state.
Save()
// SaveLayerAlpha saves a new layer with the given opacity (0.0 to 1.0).
// All drawing until the matching Restore() call will be composited with this opacity.
SaveLayerAlpha(bounds Rect, alpha float64)
// SaveLayer saves a new offscreen layer for group compositing effects.
//
// All drawing until the matching Restore() is captured in the layer,
// then composited back using the paint's BlendMode and Alpha.
// This enables effects like drawing multiple shapes that blend as a group.
//
// bounds defines the layer extent; pass Rect{} for unbounded.
// If paint is nil, behaves like Save() with no special compositing.
SaveLayer(bounds Rect, paint *Paint)
// Restore pops the most recent transform and clip state.
Restore()
// Translate moves the origin by the given offset.
Translate(dx, dy float64)
// Scale scales the coordinate system by the given factors.
Scale(sx, sy float64)
// Rotate rotates the coordinate system by radians.
Rotate(radians float64)
// ClipRect restricts future drawing to the given rectangle.
ClipRect(rect Rect)
// ClipRRect restricts future drawing to the given rounded rectangle.
ClipRRect(rrect RRect)
// ClipPath restricts future drawing to an arbitrary path shape.
//
// op controls how the path combines with any existing clip:
// - ClipOpIntersect: only draw where both old clip and path overlap
// - ClipOpDifference: cut the path shape out of the drawable area
//
// antialias enables smooth edges; disable for pixel-perfect hard edges.
// The path's FillRule determines how self-intersecting paths are filled.
//
// With a nil or empty path:
// - ClipOpIntersect: results in an empty clip (nothing visible)
// - ClipOpDifference: leaves the clip unchanged (subtracting nothing)
ClipPath(path *Path, op ClipOp, antialias bool)
// Clear fills the entire canvas with the given color.
Clear(color Color)
// DrawRect draws a rectangle with the provided paint.
DrawRect(rect Rect, paint Paint)
// DrawRRect draws a rounded rectangle with the provided paint.
DrawRRect(rrect RRect, paint Paint)
// DrawCircle draws a circle with the provided paint.
DrawCircle(center Offset, radius float64, paint Paint)
// DrawLine draws a line segment with the provided paint.
DrawLine(start, end Offset, paint Paint)
// DrawText draws a pre-shaped text layout at the given position.
DrawText(layout *TextLayout, position Offset)
// DrawImage draws an image with its top-left corner at the given position.
DrawImage(image image.Image, position Offset)
// DrawImageRect draws an image from srcRect to dstRect with sampling quality.
// srcRect selects the source region (zero rect = entire image).
// cacheKey enables SkImage caching; pass 0 to disable, or a unique ID that
// changes when the underlying pixel data changes.
DrawImageRect(img image.Image, srcRect, dstRect Rect, quality FilterQuality, cacheKey uintptr)
// DrawPath draws a path with the provided paint.
DrawPath(path *Path, paint Paint)
// DrawRectShadow draws a shadow behind a rectangle.
DrawRectShadow(rect Rect, shadow BoxShadow)
// DrawRRectShadow draws a shadow behind a rounded rectangle.
DrawRRectShadow(rrect RRect, shadow BoxShadow)
// SaveLayerBlur saves a layer with a backdrop blur effect.
// Content drawn before this call will be blurred within the bounds.
// Call Restore() to apply the blur and pop the layer.
SaveLayerBlur(bounds Rect, sigmaX, sigmaY float64)
// DrawSVG renders an SVG DOM within the given bounds.
// svgPtr must be the C handle from SVGDOM.Ptr(), not a Go pointer.
// The SVG is positioned at bounds.Left/Top and sized to bounds width/height.
// No-op if bounds has zero or negative dimensions.
DrawSVG(svgPtr unsafe.Pointer, bounds Rect)
// DrawSVGTinted renders an SVG DOM within the given bounds with an optional tint color.
// The tint color replaces all SVG colors while preserving alpha (SrcIn blend mode).
// If tintColor is 0 (ColorTransparent), renders without tinting.
// Note: Tinting affects ALL SVG content including gradients and embedded images.
DrawSVGTinted(svgPtr unsafe.Pointer, bounds Rect, tintColor Color)
// DrawLottie renders a Lottie animation frame within the given bounds.
// animPtr must be the C handle from Skottie.Ptr(), not a Go pointer.
// t is the normalized time (0.0 to 1.0) representing animation progress.
// The animation is positioned at bounds.Left/Top and sized to bounds width/height.
DrawLottie(animPtr unsafe.Pointer, bounds Rect, t float64)
// EmbedPlatformView records a platform view at the current canvas position.
// During compositing, the canvas resolves transform+clip and updates native geometry.
EmbedPlatformView(viewID int64, size Size)
// Size returns the size of the canvas in pixels.
Size() Size
}
type ClipOp
ClipOp specifies how a new clip shape combines with the existing clip region.
Clips are cumulative within a Save/Restore pair. Each clip operation further restricts the drawable area based on the chosen operation.
type ClipOp int
const (
ClipOpIntersect ClipOp = iota // Restrict to intersection of old and new clips
ClipOpDifference // Subtract new shape from old clip (creates holes)
)
func (ClipOp) String
func (o ClipOp) String() string
String returns a human-readable representation of the clip operation.
type Color
Color is stored as ARGB (0xAARRGGBB).
type Color uint32
func RGB
func RGB(r, g, b uint8) Color
RGB constructs an opaque Color from red, green, blue bytes.
func RGBA
func RGBA(r, g, b uint8, a float64) Color
RGBA constructs a Color from red, green, blue bytes and alpha (0-1).
func RGBA8
func RGBA8(r, g, b, a uint8) Color
RGBA8 constructs a Color from red, green, blue, alpha bytes (all 0-255).
func (Color) Alpha
func (c Color) Alpha() float64
Alpha returns the alpha component as a value from 0.0 (transparent) to 1.0 (opaque).
func (Color) RGBAF
func (c Color) RGBAF() (r, g, b, a float64)
RGBAF returns normalized color components (0.0 to 1.0).
func (Color) WithAlpha
func (c Color) WithAlpha(a float64) Color
WithAlpha returns a copy of the color with the given alpha (0-1).
func (Color) WithAlpha8
func (c Color) WithAlpha8(a uint8) Color
WithAlpha8 returns a copy of the color with the given alpha byte (0-255).
type ColorFilter
ColorFilter transforms colors during graphics.
ColorFilters modify pixel colors as they pass through the rendering pipeline. They can be used for effects like tinting, grayscale conversion, brightness adjustment, and color correction.
Filters can be chained using the Compose method. When composed, the inner filter is applied first, then the outer filter processes the result.
To apply a ColorFilter, set it on a Paint and pass that Paint to SaveLayer. The filter is applied when the layer is composited back to the parent.
Filter chains must be acyclic. Creating cycles (e.g., setting Inner to point back to the same filter) causes infinite recursion. Use the Compose method to safely build chains.
type ColorFilter struct {
// Type specifies the filter algorithm.
Type ColorFilterType
// Color is the constant color for ColorFilterBlend.
Color Color
// BlendMode controls how Color is blended for ColorFilterBlend.
BlendMode BlendMode
// Matrix is a 5x4 color transformation matrix for ColorFilterMatrix.
// The matrix is stored in row-major order as [R, G, B, A, translate] for
// each output channel:
//
// R' = Matrix[0]*R + Matrix[1]*G + Matrix[2]*B + Matrix[3]*A + Matrix[4]
// G' = Matrix[5]*R + Matrix[6]*G + Matrix[7]*B + Matrix[8]*A + Matrix[9]
// B' = Matrix[10]*R + Matrix[11]*G + Matrix[12]*B + Matrix[13]*A + Matrix[14]
// A' = Matrix[15]*R + Matrix[16]*G + Matrix[17]*B + Matrix[18]*A + Matrix[19]
//
// Input values are in the range [0, 255]. Translation values (indices 4, 9,
// 14, 19) are added after multiplication.
Matrix [20]float64
// Inner is an optional filter to apply before this one.
// Used for filter composition chains.
Inner *ColorFilter
}
func ColorFilterBrightness
func ColorFilterBrightness(factor float64) ColorFilter
ColorFilterBrightness creates a color filter that scales RGB values.
A factor of 1.0 leaves colors unchanged. Values greater than 1.0 brighten the image, while values less than 1.0 darken it. Alpha is preserved.
func ColorFilterDisabled
func ColorFilterDisabled() ColorFilter
ColorFilterDisabled creates a color filter suitable for disabled UI states.
Combines grayscale conversion with 38% opacity, matching Material Design guidelines for disabled components.
func ColorFilterGrayscale
func ColorFilterGrayscale() ColorFilter
ColorFilterGrayscale creates a color filter that converts colors to grayscale.
Uses the ITU-R BT.709 luminance formula: gray = 0.2126*R + 0.7152*G + 0.0722*B
func ColorFilterInvert
func ColorFilterInvert() ColorFilter
ColorFilterInvert creates a color filter that inverts RGB values. Alpha is preserved.
func ColorFilterSaturate
func ColorFilterSaturate(factor float64) ColorFilter
ColorFilterSaturate creates a color filter that adjusts color saturation.
A factor of 1.0 leaves colors unchanged. A factor of 0.0 produces grayscale. Values greater than 1.0 increase saturation. Uses the SVG saturate matrix algorithm based on ITU-R BT.709 luminance coefficients.
func ColorFilterSepia
func ColorFilterSepia() ColorFilter
ColorFilterSepia creates a color filter that applies a warm sepia tone.
func ColorFilterTint
func ColorFilterTint(color Color, mode BlendMode) ColorFilter
ColorFilterTint creates a color filter that blends a constant color with the input using the specified blend mode.
Common blend modes for tinting:
- BlendModeSrcIn: replaces color in opaque areas, useful for icons
- BlendModeSrcATop: tints while preserving original transparency
- BlendModeMultiply: multiplies colors, darkening the result
func (ColorFilter) Compose
func (cf ColorFilter) Compose(inner ColorFilter) ColorFilter
Compose returns a new ColorFilter that applies inner first, then this filter.
The returned filter is independent of the inputs; modifying inner after calling Compose does not affect the composed filter.
type ColorFilterType
ColorFilterType specifies the algorithm used by a ColorFilter.
type ColorFilterType int
const (
// ColorFilterBlend blends a constant color with the input using a blend mode.
// Requires Color and BlendMode fields to be set.
ColorFilterBlend ColorFilterType = iota
// ColorFilterMatrix applies a 5x4 color transformation matrix.
// Requires the Matrix field to be set.
ColorFilterMatrix
)
type DashPattern
DashPattern defines a stroke dash pattern as alternating on/off lengths.
The pattern repeats along the stroke. For example, Intervals of [10, 5] draws 10 pixels on, 5 pixels off, repeating. Intervals of [10, 5, 5, 5] draws 10 on, 5 off, 5 on, 5 off, repeating.
type DashPattern struct {
Intervals []float64 // Alternating on/off lengths; must have even count >= 2, all > 0
Phase float64 // Starting offset into the pattern in pixels
}
type DisplayList
DisplayList is an immutable list of drawing operations. It can be replayed onto any Canvas implementation.
type DisplayList struct {
// contains filtered or unexported fields
}
func (*DisplayList) Dispose
func (d *DisplayList) Dispose()
Dispose releases debug tracking for SVG pointers in this display list. In release builds this is a no-op. In debug builds (-tags svgdebug) it decrements the refcount for tracked SVG pointers. Call this when a cached display list is being replaced or discarded.
func (*DisplayList) Paint
func (d *DisplayList) Paint(canvas Canvas)
Paint replays the recorded operations onto the provided canvas. On platforms with Skia (android, darwin, ios), batchable ops are encoded into a command buffer and replayed in a single CGO call for performance.
func (*DisplayList) Size
func (d *DisplayList) Size() Size
Size returns the size recorded when the display list was created.
type FilterQuality
FilterQuality controls image sampling quality during scaling.
type FilterQuality int
const (
FilterQualityNone FilterQuality = iota // Nearest neighbor (pixelated)
FilterQualityLow // Bilinear
FilterQualityMedium // Bilinear + mipmaps
FilterQualityHigh // Bicubic (Mitchell)
)
func (FilterQuality) String
func (q FilterQuality) String() string
String returns a human-readable representation of the filter quality.
type FontManager
FontManager manages font registration for text graphics.
type FontManager struct {
// contains filtered or unexported fields
}
func DefaultFontManager
func DefaultFontManager() *FontManager
DefaultFontManager returns a shared font manager with a bundled font. For backward compatibility, returns nil on error.
func DefaultFontManagerErr
func DefaultFontManagerErr() (*FontManager, error)
DefaultFontManagerErr returns a shared font manager with a bundled font. It returns both the manager and any error that occurred during initialization.
func NewFontManager
func NewFontManager() (*FontManager, error)
NewFontManager creates a font manager using system defaults.
func (*FontManager) Face
func (m *FontManager) Face(style TextStyle) (font.Face, error)
Face resolves a font face for the given style. Skia-backed builds do not expose font.Face instances.
func (*FontManager) RegisterFont
func (m *FontManager) RegisterFont(name string, data []byte) error
RegisterFont registers a new font family from TrueType data.
type FontStyle
FontStyle represents normal or italic text styles.
type FontStyle int
const (
// FontStyleNormal selects the upright (roman) variant of the typeface.
FontStyleNormal FontStyle = 1
// FontStyleItalic selects the italic variant of the typeface.
FontStyleItalic FontStyle = 2
)
func (FontStyle) String
func (s FontStyle) String() string
String returns a human-readable representation of the font style.
type FontWeight
FontWeight represents a numeric font weight.
type FontWeight int
const (
FontWeightThin FontWeight = 100
FontWeightExtraLight FontWeight = 200
FontWeightLight FontWeight = 300
FontWeightNormal FontWeight = 400
FontWeightMedium FontWeight = 500
FontWeightSemibold FontWeight = 600
FontWeightBold FontWeight = 700
FontWeightExtraBold FontWeight = 800
FontWeightBlack FontWeight = 900
)
func (FontWeight) String
func (w FontWeight) String() string
String returns a human-readable representation of the font weight.
type Gradient
Gradient describes a linear or radial gradient.
Use NewLinearGradient or NewRadialGradient to construct gradients.
type Gradient struct {
// Type indicates whether this is a linear or radial gradient.
Type GradientType
// Linear contains the linear gradient configuration when Type is GradientTypeLinear.
Linear LinearGradient
// Radial contains the radial gradient configuration when Type is GradientTypeRadial.
Radial RadialGradient
}
func NewLinearGradient
func NewLinearGradient(start, end Alignment, stops []GradientStop) *Gradient
NewLinearGradient constructs a linear gradient definition using relative coordinates.
The start and end points use the Alignment coordinate system where (-1, -1) is the top-left corner, (0, 0) is the center, and (1, 1) is the bottom-right corner.
Example:
// Horizontal gradient from left to right
graphics.NewLinearGradient(
graphics.AlignCenterLeft,
graphics.AlignCenterRight,
[]graphics.GradientStop{
{Position: 0, Color: startColor},
{Position: 1, Color: endColor},
},
)
func NewRadialGradient
func NewRadialGradient(center Alignment, radius float64, stops []GradientStop) *Gradient
NewRadialGradient constructs a radial gradient definition using relative coordinates.
The center point uses the Alignment coordinate system where (-1, -1) is the top-left corner, (0, 0) is the center, and (1, 1) is the bottom-right corner.
The radius is relative to half the minimum dimension of the bounding rectangle, so a radius of 1.0 will touch the nearest edge from the center, and 2.0 will extend to the farthest corner of a square widget.
Example:
// Radial gradient centered in widget, filling to edges
graphics.NewRadialGradient(
graphics.AlignCenter,
1.0, // touches nearest edge
[]graphics.GradientStop{
{Position: 0, Color: centerColor},
{Position: 1, Color: edgeColor},
},
)
func (*Gradient) Bounds
func (g *Gradient) Bounds(widgetRect Rect) Rect
Bounds returns the rectangle needed to fully render the gradient, expanded from widgetRect as needed. The result is the union of widgetRect and the gradient's natural bounds, ensuring it never shrinks widgetRect.
For radial gradients, the natural bounds are a square centered on the resolved gradient center with sides equal to twice the resolved radius.
For linear gradients, the natural bounds span from the resolved start to end points.
This method is used by widgets with overflow visible to determine the drawing area for gradient overflow effects like glows.
func (*Gradient) IsValid
func (g *Gradient) IsValid() bool
IsValid reports whether the gradient has usable stops.
func (*Gradient) Stops
func (g *Gradient) Stops() []GradientStop
Stops returns the gradient stops for the configured type.
type GradientStop
GradientStop defines a color stop within a gradient.
Each stop specifies a color at a position along the gradient. Colors are interpolated between stops to create smooth transitions.
Example:
[]graphics.GradientStop{
{Position: 0.0, Color: graphics.RGB(255, 0, 0)}, // Red at start
{Position: 0.5, Color: graphics.RGB(255, 255, 0)}, // Yellow at midpoint
{Position: 1.0, Color: graphics.RGB(0, 255, 0)}, // Green at end
}
type GradientStop struct {
// Position is where this color appears along the gradient, from 0.0 (start)
// to 1.0 (end). For linear gradients, 0.0 is the Start point and 1.0 is
// the End point. For radial gradients, 0.0 is the center and 1.0 is at
// the radius edge.
Position float64
// Color is the color at this position.
Color Color
}
type GradientType
GradientType describes the gradient variant.
type GradientType int
const (
// GradientTypeNone indicates no gradient is applied.
GradientTypeNone GradientType = iota
// GradientTypeLinear indicates a linear gradient.
GradientTypeLinear
// GradientTypeRadial indicates a radial gradient.
GradientTypeRadial
)
func (GradientType) String
func (t GradientType) String() string
String returns a human-readable representation of the gradient type.
type ImageFilter
ImageFilter applies pixel-based effects to rendered content.
ImageFilters operate on the rendered pixels rather than individual colors. They enable effects like blur, drop shadows, and other post-processing.
Filters can be chained using the Compose method. When composed, the input filter is applied first, then this filter processes the result.
To apply an ImageFilter, set it on a Paint and pass that Paint to SaveLayer. The filter processes all drawing operations within the layer when it is composited back to the parent.
Filter chains must be acyclic. Creating cycles causes infinite recursion. Use the Compose method to safely build chains.
type ImageFilter struct {
// Type specifies the filter algorithm.
Type ImageFilterType
// SigmaX is the horizontal blur radius for ImageFilterBlur and
// ImageFilterDropShadow. Larger values produce more blur.
SigmaX float64
// SigmaY is the vertical blur radius for ImageFilterBlur and
// ImageFilterDropShadow. Larger values produce more blur.
SigmaY float64
// TileMode controls edge handling for ImageFilterBlur.
TileMode TileMode
// OffsetX is the horizontal shadow offset for ImageFilterDropShadow.
// Positive values move the shadow right.
OffsetX float64
// OffsetY is the vertical shadow offset for ImageFilterDropShadow.
// Positive values move the shadow down.
OffsetY float64
// Color is the shadow color for ImageFilterDropShadow.
Color Color
// ShadowOnly, when true, renders only the shadow without the original
// content. Used by ImageFilterDropShadow.
ShadowOnly bool
// ColorFilter is the filter to apply for ImageFilterColorFilter.
ColorFilter *ColorFilter
// Input is an optional filter to apply before this one.
// Used for filter composition chains.
Input *ImageFilter
}
func NewBlurFilter
func NewBlurFilter(sigmaX, sigmaY float64) ImageFilter
NewBlurFilter creates a Gaussian blur image filter.
SigmaX and sigmaY specify the blur radius in pixels for each axis. Larger values produce stronger blur. The filter uses TileModeDecal by default, treating pixels outside the bounds as transparent.
func NewBlurFilterUniform
func NewBlurFilterUniform(sigma float64) ImageFilter
NewBlurFilterUniform creates a Gaussian blur with equal horizontal and vertical blur radius.
func NewDropShadowFilter
func NewDropShadowFilter(dx, dy, sigma float64, color Color) ImageFilter
NewDropShadowFilter creates a drop shadow effect that renders both the shadow and the original content.
The shadow is offset by (dx, dy) pixels from the original content and blurred by sigma pixels. Positive dx moves the shadow right; positive dy moves it down.
func NewDropShadowOnlyFilter
func NewDropShadowOnlyFilter(dx, dy, sigma float64, color Color) ImageFilter
NewDropShadowOnlyFilter creates a drop shadow effect that renders only the shadow, without the original content.
This is useful for creating shadow layers that are composited separately from the content.
func NewImageFilterFromColorFilter
func NewImageFilterFromColorFilter(cf ColorFilter) ImageFilter
NewImageFilterFromColorFilter wraps a ColorFilter as an ImageFilter.
This allows ColorFilters to be composed with other ImageFilters in a filter chain.
func (ImageFilter) Compose
func (imf ImageFilter) Compose(input ImageFilter) ImageFilter
Compose returns a new ImageFilter that applies input first, then this filter.
The returned filter is independent of the inputs; modifying input after calling Compose does not affect the composed filter.
func (ImageFilter) WithTileMode
func (imf ImageFilter) WithTileMode(mode TileMode) ImageFilter
WithTileMode returns a copy of the filter with the specified tile mode.
Tile mode only affects ImageFilterBlur. Other filter types ignore it.
type ImageFilterType
ImageFilterType specifies the algorithm used by an ImageFilter.
type ImageFilterType int
const (
// ImageFilterBlur applies a Gaussian blur effect.
// Requires SigmaX and SigmaY fields to be set.
ImageFilterBlur ImageFilterType = iota
// ImageFilterDropShadow renders a shadow behind the content.
// Requires OffsetX, OffsetY, SigmaX, SigmaY, and Color fields.
ImageFilterDropShadow
// ImageFilterColorFilter applies a ColorFilter as an image filter.
// Requires the ColorFilter field to be set.
ImageFilterColorFilter
)
type Layer
Layer represents a cached drawing surface for a repaint boundary. Layers have stable identity - never replace the object, only mark dirty. Parent layers contain references to child layers via DrawChildLayer ops, not embedded content. This allows child content to change without requiring parent re-recording.
type Layer struct {
// Content is the recorded display list (includes DrawChildLayer ops)
Content *DisplayList
// Dirty indicates this layer needs re-recording
Dirty bool
// Size of this layer's bounds
Size Size
}
func (*Layer) Composite
func (l *Layer) Composite(canvas Canvas)
Composite draws this layer to the canvas. Child layers are drawn via DrawChildLayer ops within Content.
func (*Layer) Dispose
func (l *Layer) Dispose()
Dispose releases resources held by this layer. Call this when the layer is no longer needed (e.g., boundary removed from tree).
func (*Layer) MarkDirty
func (l *Layer) MarkDirty()
MarkDirty marks this layer for re-recording.
func (*Layer) SetContent
func (l *Layer) SetContent(content *DisplayList)
SetContent replaces the layer's content, disposing the old content first. This should be called when re-recording a layer.
func (*Layer) String
func (l *Layer) String() string
String returns a debug representation of the layer.
type LinearGradient
LinearGradient defines a gradient between two points using relative coordinates.
Start and End use the Alignment coordinate system where (-1, -1) is the top-left corner, (0, 0) is the center, and (1, 1) is the bottom-right corner. This allows gradients to scale with widget dimensions.
Common gradient directions:
Horizontal: AlignCenterLeft to AlignCenterRight
Vertical: AlignTopCenter to AlignBottomCenter
Diagonal: AlignTopLeft to AlignBottomRight
type LinearGradient struct {
// Start is the starting point of the gradient in relative coordinates.
Start Alignment
// End is the ending point of the gradient in relative coordinates.
End Alignment
// Stops defines the color stops along the gradient.
Stops []GradientStop
}
type OcclusionCanvas
OcclusionCanvas is an optional interface for canvases that support platform view occlusion regions. GeometryCanvas implements this to track z-order occlusion during the geometry compositing pass.
type OcclusionCanvas interface {
OccludePlatformViews(mask *Path)
}
type Offset
Offset represents a 2D point or vector in pixel coordinates.
type Offset struct {
X float64
Y float64
}
type Paint
Paint describes how to draw a shape on the canvas.
A zero-value Paint draws nothing (BlendModeClear with Alpha 0). Use DefaultPaint for a basic opaque white fill.
type Paint struct {
Color Color
Gradient *Gradient // If set, overrides Color
// GradientBounds optionally specifies the bounds to use for resolving
// gradient Alignment coordinates. If nil, the shape's drawing bounds are used.
// Set this when drawing to an expanded area (e.g., for overflow effects)
// but wanting the gradient to align to the original widget bounds.
GradientBounds *Rect
Style PaintStyle // Fill, stroke, or both
StrokeWidth float64 // Width of stroke in pixels
// Stroke styling (only applies when Style includes stroke)
StrokeCap StrokeCap // How endpoints are drawn; 0 = CapButt
StrokeJoin StrokeJoin // How corners are drawn; 0 = JoinMiter
MiterLimit float64 // Miter join limit before beveling; 0 defaults to 4.0
Dash *DashPattern // Dash pattern; nil = solid stroke
// Compositing
BlendMode BlendMode // Compositing mode; negative defaults to BlendModeSrcOver
Alpha float64 // Overall opacity 0.0-1.0; negative defaults to 1.0
// Filters (only applied via SaveLayer, not individual draw calls)
//
// ColorFilter transforms colors when the layer is composited. Use with
// SaveLayer to apply effects like tinting, grayscale, or brightness
// adjustment to grouped content.
ColorFilter *ColorFilter
// ImageFilter applies pixel-based effects when the layer is composited.
// Use with SaveLayer to apply blur, drop shadow, or other effects to
// grouped content.
ImageFilter *ImageFilter
}
func DefaultPaint
func DefaultPaint() Paint
DefaultPaint returns a basic opaque white fill paint with standard compositing.
type PaintStyle
PaintStyle describes how shapes are filled or stroked.
type PaintStyle int
const (
// PaintStyleFill fills the shape interior.
PaintStyleFill PaintStyle = iota
// PaintStyleStroke draws only the outline.
PaintStyleStroke
// PaintStyleFillAndStroke fills and then strokes the outline.
PaintStyleFillAndStroke
)
func (PaintStyle) String
func (s PaintStyle) String() string
String returns a human-readable representation of the paint style.
type ParagraphOptions
ParagraphOptions controls paragraph-level layout behavior such as line wrapping, line limits, and horizontal alignment. The zero value produces an unconstrained, left-aligned, single-pass layout.
type ParagraphOptions struct {
// MaxWidth is the width available for line wrapping.
// 0 means no width constraint (text will not wrap).
MaxWidth float64
// MaxLines limits the number of visible lines.
// 0 means unlimited (all lines are shown).
MaxLines int
// TextAlign controls horizontal alignment of lines within the paragraph.
// The zero value ([TextAlignLeft]) aligns lines to the left edge.
TextAlign TextAlign
}
type Path
Path represents a vector path for drawing or clipping arbitrary shapes.
Build paths using MoveTo, LineTo, QuadTo, CubicTo, and Close methods. Use with Canvas.DrawPath to stroke/fill, or Canvas.ClipPath to clip.
type Path struct {
Commands []PathCommand
FillRule PathFillRule
}
func CopyPath
func CopyPath(p *Path) *Path
CopyPath creates a fully independent copy of a Path, including all command arguments. Returns nil if path is nil.
func NewPath
func NewPath() *Path
NewPath creates a new empty path with nonzero fill rule.
func NewPathWithFillRule
func NewPathWithFillRule(fillRule PathFillRule) *Path
NewPathWithFillRule creates a new empty path with the specified fill rule.
func (*Path) AddRRect
func (p *Path) AddRRect(rr RRect)
AddRRect appends a rounded rectangle to the path using cubic bezier curves for the corners. Each corner radius is handled independently, matching the RRect's per-corner Radius values. Straight edges use LineTo; corners use CubicTo with the standard circular approximation constant (kappa).
func (*Path) AddRect
func (p *Path) AddRect(r Rect)
AddRect appends a clockwise rectangle (M + 3L + Z) to the path.
func (*Path) Bounds
func (p *Path) Bounds() Rect
Bounds returns the bounding rectangle of the path. Returns an empty Rect if the path has no points.
func (*Path) Clear
func (p *Path) Clear()
Clear removes all commands from the path.
func (*Path) Close
func (p *Path) Close()
Close closes the current subpath by drawing a line to the starting point.
func (*Path) CubicTo
func (p *Path) CubicTo(x1, y1, x2, y2, x3, y3 float64)
CubicTo adds a cubic bezier curve from the current point to (x3, y3) with control points (x1, y1) and (x2, y2).
func (*Path) IsEmpty
func (p *Path) IsEmpty() bool
IsEmpty returns true if the path has no commands.
func (*Path) LineTo
func (p *Path) LineTo(x, y float64)
LineTo adds a line segment from the current point to (x, y).
func (*Path) MoveTo
func (p *Path) MoveTo(x, y float64)
MoveTo starts a new subpath at the given point.
func (*Path) QuadTo
func (p *Path) QuadTo(x1, y1, x2, y2 float64)
QuadTo adds a quadratic bezier curve from the current point to (x2, y2) with control point (x1, y1).
func (*Path) Translate
func (p *Path) Translate(dx, dy float64) *Path
Translate returns a new path with all coordinates offset by (dx, dy).
type PathCommand
PathCommand represents a single path operation with its coordinate arguments.
type PathCommand struct {
Op PathOp // The operation type
Args []float64 // Coordinates: MoveTo/LineTo=[x,y], QuadTo=[x1,y1,x2,y2], CubicTo=[x1,y1,x2,y2,x3,y3]
}
type PathFillRule
PathFillRule determines how path interiors are calculated for filling.
type PathFillRule int
const (
// FillRuleNonZero fills regions with nonzero winding count.
// A point is inside if a ray from it crosses more left-to-right edges
// than right-to-left edges (or vice versa).
FillRuleNonZero PathFillRule = iota
// FillRuleEvenOdd fills regions crossed an odd number of times.
// Useful for creating holes: nested shapes alternate between filled/unfilled.
FillRuleEvenOdd
)
func (PathFillRule) String
func (r PathFillRule) String() string
String returns a human-readable representation of the path fill rule.
type PathOp
PathOp represents a path drawing operation type.
type PathOp int
const (
PathOpMoveTo PathOp = iota // Start new subpath at point (x, y)
PathOpLineTo // Draw line to point (x, y)
PathOpQuadTo // Draw quadratic curve to (x2, y2) via control (x1, y1)
PathOpCubicTo // Draw cubic curve to (x3, y3) via controls (x1, y1), (x2, y2)
PathOpClose // Close subpath with line to start point
)
func (PathOp) String
func (o PathOp) String() string
String returns a human-readable representation of the path operation.
type PictureRecorder
PictureRecorder records drawing commands into a display list.
type PictureRecorder struct {
// contains filtered or unexported fields
}
func (*PictureRecorder) BeginRecording
func (r *PictureRecorder) BeginRecording(size Size) Canvas
BeginRecording starts a new recording session.
func (*PictureRecorder) DrawChildLayer
func (r *PictureRecorder) DrawChildLayer(layer *Layer)
DrawChildLayer records a reference to a child repaint boundary's layer. When the display list is replayed during compositing, the child layer's content is composited at the current canvas transform and clip state.
func (*PictureRecorder) EndRecording
func (r *PictureRecorder) EndRecording() *DisplayList
EndRecording finishes the recording and returns a display list.
type RRect
RRect represents a rounded rectangle with per-corner radii.
type RRect struct {
Rect Rect
TopLeft Radius
TopRight Radius
BottomRight Radius
BottomLeft Radius
}
func RRectFromRectAndRadius
func RRectFromRectAndRadius(rect Rect, radius Radius) RRect
RRectFromRectAndRadius creates a rounded rectangle with uniform corner radii.
func (RRect) UniformRadius
func (r RRect) UniformRadius() float64
UniformRadius returns a single radius value if all corners match, or 0 if not.
type RadialGradient
RadialGradient defines a gradient radiating from a center point.
Center uses the Alignment coordinate system where (-1, -1) is the top-left corner, (0, 0) is the center, and (1, 1) is the bottom-right corner.
Radius is relative to half the minimum dimension of the bounding rectangle, so a radius of 1.0 will touch the nearest edge from the center.
type RadialGradient struct {
// Center is the center point of the gradient in relative coordinates.
Center Alignment
// Radius is the relative radius (1.0 = half the min dimension).
Radius float64
// Stops defines the color stops along the gradient.
Stops []GradientStop
}
type Radius
Radius represents corner radii for rounded rectangles.
type Radius struct {
X float64
Y float64
}
func CircularRadius
func CircularRadius(value float64) Radius
CircularRadius creates a circular radius with equal X/Y values.
type Rect
Rect represents a rectangle using left, top, right, bottom coordinates.
type Rect struct {
Left float64
Top float64
Right float64
Bottom float64
}
func RectFromLTWH
func RectFromLTWH(left, top, width, height float64) Rect
RectFromLTWH constructs a Rect from left, top, width, height values.
func (Rect) Center
func (r Rect) Center() Offset
Center returns the center point of the rectangle.
func (Rect) Height
func (r Rect) Height() float64
Height returns the height of the rectangle.
func (Rect) Intersect
func (r Rect) Intersect(other Rect) Rect
Intersect returns the intersection of two rectangles. Returns empty rect if they don't overlap.
func (Rect) Intersects
func (r Rect) Intersects(other Rect) bool
Intersects returns true if the two rectangles overlap. Returns false if either rectangle is empty.
func (Rect) IsEmpty
func (r Rect) IsEmpty() bool
IsEmpty returns true if the rectangle has zero or negative area.
func (Rect) Size
func (r Rect) Size() Size
Size returns the size of the rectangle.
func (Rect) Translate
func (r Rect) Translate(dx, dy float64) Rect
Translate returns a new rect offset by (dx, dy).
func (Rect) Union
func (r Rect) Union(other Rect) Rect
Union returns the smallest rect containing both r and other.
func (Rect) Width
func (r Rect) Width() float64
Width returns the width of the rectangle.
type Size
Size represents width and height dimensions in pixels.
type Size struct {
Width float64
Height float64
}
type SkiaCanvas
SkiaCanvas implements Canvas using the Skia backend.
type SkiaCanvas struct {
// contains filtered or unexported fields
}
func NewSkiaCanvas
func NewSkiaCanvas(canvas unsafe.Pointer, size Size) *SkiaCanvas
NewSkiaCanvas wraps a Skia canvas pointer as a Canvas.
func (*SkiaCanvas) Clear
func (c *SkiaCanvas) Clear(color Color)
func (*SkiaCanvas) ClipPath
func (c *SkiaCanvas) ClipPath(path *Path, op ClipOp, antialias bool)
func (*SkiaCanvas) ClipRRect
func (c *SkiaCanvas) ClipRRect(rrect RRect)
func (*SkiaCanvas) ClipRect
func (c *SkiaCanvas) ClipRect(rect Rect)
func (*SkiaCanvas) DrawCircle
func (c *SkiaCanvas) DrawCircle(center Offset, radius float64, paint Paint)
func (*SkiaCanvas) DrawImage
func (c *SkiaCanvas) DrawImage(img image.Image, position Offset)
func (*SkiaCanvas) DrawImageRect
func (c *SkiaCanvas) DrawImageRect(img image.Image, srcRect, dstRect Rect, quality FilterQuality, cacheKey uintptr)
func (*SkiaCanvas) DrawLine
func (c *SkiaCanvas) DrawLine(start, end Offset, paint Paint)
func (*SkiaCanvas) DrawLottie
func (c *SkiaCanvas) DrawLottie(animPtr unsafe.Pointer, bounds Rect, t float64)
func (*SkiaCanvas) DrawPath
func (c *SkiaCanvas) DrawPath(path *Path, paint Paint)
func (*SkiaCanvas) DrawRRect
func (c *SkiaCanvas) DrawRRect(rrect RRect, paint Paint)
func (*SkiaCanvas) DrawRRectShadow
func (c *SkiaCanvas) DrawRRectShadow(rrect RRect, shadow BoxShadow)
func (*SkiaCanvas) DrawRect
func (c *SkiaCanvas) DrawRect(rect Rect, paint Paint)
func (*SkiaCanvas) DrawRectShadow
func (c *SkiaCanvas) DrawRectShadow(rect Rect, shadow BoxShadow)
func (*SkiaCanvas) DrawSVG
func (c *SkiaCanvas) DrawSVG(svgPtr unsafe.Pointer, bounds Rect)
func (*SkiaCanvas) DrawSVGTinted
func (c *SkiaCanvas) DrawSVGTinted(svgPtr unsafe.Pointer, bounds Rect, tintColor Color)
func (*SkiaCanvas) DrawText
func (c *SkiaCanvas) DrawText(layout *TextLayout, position Offset)
func (*SkiaCanvas) EmbedPlatformView
func (c *SkiaCanvas) EmbedPlatformView(viewID int64, size Size)
func (*SkiaCanvas) Restore
func (c *SkiaCanvas) Restore()
func (*SkiaCanvas) Rotate
func (c *SkiaCanvas) Rotate(radians float64)
func (*SkiaCanvas) Save
func (c *SkiaCanvas) Save()
func (*SkiaCanvas) SaveLayer
func (c *SkiaCanvas) SaveLayer(bounds Rect, paint *Paint)
func (*SkiaCanvas) SaveLayerAlpha
func (c *SkiaCanvas) SaveLayerAlpha(bounds Rect, alpha float64)
func (*SkiaCanvas) SaveLayerBlur
func (c *SkiaCanvas) SaveLayerBlur(bounds Rect, sigmaX, sigmaY float64)
func (*SkiaCanvas) Scale
func (c *SkiaCanvas) Scale(sx, sy float64)
func (*SkiaCanvas) Size
func (c *SkiaCanvas) Size() Size
func (*SkiaCanvas) Translate
func (c *SkiaCanvas) Translate(dx, dy float64)
type SpanStyle
SpanStyle describes the visual style for a text span. During span tree flattening, zero-valued fields inherit from the parent span's resolved style. Non-zero fields override the parent. Two patterns allow children to reset inherited values:
- 1-based enums (FontStyle, TextDecorationStyle, TextDecoration): 0 = inherit, 1+ = explicit values (e.g. TextDecorationNone = 1).
- No* builder methods (TextSpan.NoLetterSpacing, TextSpan.NoWordSpacing, TextSpan.NoHeight, TextSpan.NoBackground, TextSpan.NoDecorationColor) for resetting inherited values.
type SpanStyle struct {
Color Color
FontFamily string
FontSize float64
FontWeight FontWeight
FontStyle FontStyle
LetterSpacing float64
WordSpacing float64
Height float64
Decoration TextDecoration
DecorationColor Color
DecorationStyle TextDecorationStyle
BackgroundColor Color
}
type StrokeCap
StrokeCap describes how stroke endpoints are drawn.
type StrokeCap int
const (
CapButt StrokeCap = iota // Flat edge at endpoint (default)
CapRound // Semicircle at endpoint
CapSquare // Square extending past endpoint
)
func (StrokeCap) String
func (c StrokeCap) String() string
String returns a human-readable representation of the stroke cap.
type StrokeJoin
StrokeJoin describes how stroke corners are drawn.
type StrokeJoin int
const (
JoinMiter StrokeJoin = iota // Sharp corner (default)
JoinRound // Rounded corner
JoinBevel // Flattened corner
)
func (StrokeJoin) String
func (j StrokeJoin) String() string
String returns a human-readable representation of the stroke join.
type TextAlign
TextAlign controls paragraph-level horizontal alignment for wrapped text.
Alignment only has a visible effect when the text is laid out with a constrained width (i.e., when wrapping is enabled). Without wrapping there is no paragraph width to align within.
Values are ordered to match Skia's textlayout::TextAlign enum so they can be passed through the C bridge without translation.
type TextAlign int
const (
// TextAlignLeft aligns lines to the left edge of the paragraph.
TextAlignLeft TextAlign = iota
// TextAlignRight aligns lines to the right edge of the paragraph.
TextAlignRight
// TextAlignCenter centers each line horizontally within the paragraph.
TextAlignCenter
// TextAlignJustify stretches lines so both edges are flush with the
// paragraph bounds. The last line of a paragraph is left-aligned.
TextAlignJustify
// TextAlignStart aligns lines to the start edge based on text direction.
// Currently behaves like [TextAlignLeft] (LTR only).
TextAlignStart
// TextAlignEnd aligns lines to the end edge based on text direction.
// Currently behaves like [TextAlignRight] (LTR only).
TextAlignEnd
)
func (TextAlign) String
func (a TextAlign) String() string
String returns a human-readable representation of the text alignment.
type TextDecoration
TextDecoration selects a single text decoration line. Like FontStyle and TextDecorationStyle, the zero value means "inherit from parent."
type TextDecoration int
const (
// TextDecorationNone explicitly removes decoration, overriding any
// value inherited from a parent span.
TextDecorationNone TextDecoration = 1
// TextDecorationUnderline draws a line below the text baseline.
TextDecorationUnderline TextDecoration = 2
// TextDecorationOverline draws a line above the text.
TextDecorationOverline TextDecoration = 3
// TextDecorationLineThrough draws a line through the middle of the text.
TextDecorationLineThrough TextDecoration = 4
)
type TextDecorationStyle
TextDecorationStyle controls the appearance of decoration lines.
type TextDecorationStyle int
const (
// TextDecorationStyleSolid draws a single continuous line.
TextDecorationStyleSolid TextDecorationStyle = 1
// TextDecorationStyleDouble draws two parallel lines.
TextDecorationStyleDouble TextDecorationStyle = 2
// TextDecorationStyleDotted draws a dotted line.
TextDecorationStyleDotted TextDecorationStyle = 3
// TextDecorationStyleDashed draws a dashed line.
TextDecorationStyleDashed TextDecorationStyle = 4
// TextDecorationStyleWavy draws a sinusoidal wave.
TextDecorationStyleWavy TextDecorationStyle = 5
)
type TextLayout
TextLayout contains measured text metrics and a resolved font face.
type TextLayout struct {
Text string
Style TextStyle
Size Size
Ascent float64
Descent float64
Face font.Face
LineHeight float64
Lines []TextLine
// contains filtered or unexported fields
}
func LayoutRichText
func LayoutRichText(span TextSpan, baseStyle SpanStyle, manager *FontManager, opts ParagraphOptions) (*TextLayout, error)
LayoutRichText measures and shapes a tree of styled text spans. The returned TextLayout can be rendered with Canvas.DrawText, just like single-style text.
func LayoutText
func LayoutText(text string, style TextStyle, manager *FontManager) (*TextLayout, error)
LayoutText measures and shapes text using the provided font manager. It uses default paragraph options (no wrapping, left-aligned, unlimited lines). For wrapping or alignment control, use LayoutTextWithOptions.
func LayoutTextWithOptions
func LayoutTextWithOptions(text string, style TextStyle, manager *FontManager, opts ParagraphOptions) (*TextLayout, error)
LayoutTextWithOptions measures, wraps, and aligns text according to the given ParagraphOptions. The returned TextLayout contains computed metrics and a native paragraph handle for rendering.
type TextLine
TextLine represents a single laid-out line of text.
type TextLine struct {
Text string
Width float64
}
type TextShadow
TextShadow defines a shadow to draw behind text.
type TextShadow struct {
Color Color
Offset Offset
BlurRadius float64 // sigma = blurRadius * 0.5, 0 = hard shadow
}
func NewTextShadow
func NewTextShadow(color Color, blurRadius float64) *TextShadow
NewTextShadow creates a simple text shadow with the given color and blur radius. Offset defaults to (0, 2) for a subtle downward shadow.
func (TextShadow) Sigma
func (s TextShadow) Sigma() float64
Sigma returns the blur sigma for Skia's mask filter. Returns 0 if BlurRadius is zero or negative.
type TextSpan
TextSpan represents a node in a tree of styled text. A span renders its own Text first, then its Children in order. Child spans inherit style fields from their parent for any field left at its zero value.
type TextSpan struct {
Text string
Style SpanStyle
Children []TextSpan
}
func Span
func Span(text string) TextSpan
Span creates a leaf TextSpan with the given text.
func Spans
func Spans(children ...TextSpan) TextSpan
Spans creates a container TextSpan whose children are the provided spans. Style methods chained on the result set defaults inherited by all children.
func (TextSpan) Background
func (s TextSpan) Background(c Color) TextSpan
Background returns a copy with the specified background color.
func (TextSpan) Bold
func (s TextSpan) Bold() TextSpan
Bold returns a copy with FontWeight set to FontWeightBold.
func (TextSpan) Color
func (s TextSpan) Color(c Color) TextSpan
Color returns a copy with the specified text color.
func (TextSpan) DecorationColor
func (s TextSpan) DecorationColor(c Color) TextSpan
DecorationColor returns a copy with the specified decoration line color.
func (TextSpan) DecorationStyle
func (s TextSpan) DecorationStyle(style TextDecorationStyle) TextSpan
DecorationStyle returns a copy with the specified decoration line style (solid, double, dotted, dashed, or wavy).
func (TextSpan) Family
func (s TextSpan) Family(name string) TextSpan
Family returns a copy with the specified font family.
func (TextSpan) Height
func (s TextSpan) Height(v float64) TextSpan
Height returns a copy with the specified line height multiplier.
func (TextSpan) Italic
func (s TextSpan) Italic() TextSpan
Italic returns a copy with FontStyle set to FontStyleItalic.
func (TextSpan) LetterSpacing
func (s TextSpan) LetterSpacing(v float64) TextSpan
LetterSpacing returns a copy with the specified letter spacing.
func (TextSpan) NoBackground
func (s TextSpan) NoBackground() TextSpan
NoBackground returns a copy that explicitly clears background color, overriding any value inherited from a parent span.
func (TextSpan) NoDecoration
func (s TextSpan) NoDecoration() TextSpan
NoDecoration returns a copy with decoration explicitly set to none. This allows a child span to remove a decoration inherited from a parent.
func (TextSpan) NoDecorationColor
func (s TextSpan) NoDecorationColor() TextSpan
NoDecorationColor returns a copy that explicitly clears the decoration color, overriding any value inherited from a parent span. When the decoration color is unset, Skia uses the span's text color for the decoration line.
func (TextSpan) NoHeight
func (s TextSpan) NoHeight() TextSpan
NoHeight returns a copy that explicitly resets the line height multiplier to zero, overriding any value inherited from a parent span.
func (TextSpan) NoLetterSpacing
func (s TextSpan) NoLetterSpacing() TextSpan
NoLetterSpacing returns a copy that explicitly resets letter spacing to zero, overriding any value inherited from a parent span.
func (TextSpan) NoWordSpacing
func (s TextSpan) NoWordSpacing() TextSpan
NoWordSpacing returns a copy that explicitly resets word spacing to zero, overriding any value inherited from a parent span.
func (TextSpan) Overline
func (s TextSpan) Overline() TextSpan
Overline returns a copy with an overline decoration. If no DecorationColor is set on this span or any ancestor, the decoration line uses the span's text color. Use DecorationColor to set an explicit color, or NoDecorationColor to clear an inherited one.
func (TextSpan) PlainText
func (s TextSpan) PlainText() string
PlainText returns the concatenation of all text in the span tree.
func (TextSpan) Size
func (s TextSpan) Size(size float64) TextSpan
Size returns a copy with the specified font size.
func (TextSpan) Strikethrough
func (s TextSpan) Strikethrough() TextSpan
Strikethrough returns a copy with a line-through decoration. If no DecorationColor is set on this span or any ancestor, the decoration line uses the span's text color. Use DecorationColor to set an explicit color, or NoDecorationColor to clear an inherited one.
func (TextSpan) Underline
func (s TextSpan) Underline() TextSpan
Underline returns a copy with an underline decoration. If no DecorationColor is set on this span or any ancestor, the decoration line uses the span's text color. Use DecorationColor to set an explicit color, or NoDecorationColor to clear an inherited one.
func (TextSpan) Weight
func (s TextSpan) Weight(w FontWeight) TextSpan
Weight returns a copy with the specified font weight.
func (TextSpan) WithChildren
func (s TextSpan) WithChildren(children ...TextSpan) TextSpan
WithChildren returns a copy with the given child spans. Useful for adding children to a span that also carries its own text or style defaults.
func (TextSpan) WordSpacing
func (s TextSpan) WordSpacing(v float64) TextSpan
WordSpacing returns a copy with the specified word spacing.
type TextStyle
TextStyle describes how text should be rendered.
type TextStyle struct {
Color Color
Gradient *Gradient
FontFamily string
FontSize float64
FontWeight FontWeight
FontStyle FontStyle
PreserveWhitespace bool
Shadow *TextShadow
}
func (TextStyle) WithColor
func (s TextStyle) WithColor(c Color) TextStyle
WithColor returns a copy of the TextStyle with the specified color.
type TextWrap
TextWrap controls whether text wraps at the constraint width.
The zero value (TextWrapWrap) enables wrapping, which is the most common behavior for UI text. Use TextWrapNoWrap for labels, buttons, and other single-line text that should not break across lines.
type TextWrap int
const (
// TextWrapWrap wraps text at the constraint width (zero value).
TextWrapWrap TextWrap = iota
// TextWrapNoWrap renders text on a single line without wrapping.
TextWrapNoWrap
)
func (TextWrap) String
func (w TextWrap) String() string
String returns a human-readable representation of the text wrap mode.
type TileMode
TileMode specifies how an image filter handles pixels outside its bounds.
type TileMode int
const (
// TileModeClamp extends edge pixels outward.
TileModeClamp TileMode = iota
// TileModeRepeat tiles the image.
TileModeRepeat
// TileModeMirror tiles with alternating mirrored copies.
TileModeMirror
// TileModeDecal renders transparent black outside the bounds.
// This is the default for blur filters.
TileModeDecal
)
Generated by gomarkdoc