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 ContrastRatio
func ContrastRatio(a, b Color) float64
ContrastRatio returns the WCAG 2.1 contrast ratio between two colors. The result ranges from 1 (identical luminance) to 21 (black on white).
func HueChroma
func HueChroma(c Color) (hue, chroma float64)
HueChroma extracts the CAM16 hue (degrees, 0-360) and chroma from a Color under default sRGB viewing conditions.
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 ColorFromHCT
func ColorFromHCT(hue, chroma, tone float64) Color
ColorFromHCT returns the sRGB Color closest to the given HCT coordinates under default viewing conditions. Tone is clamped to [0, 100]. If the requested chroma is not achievable, it is reduced to the gamut maximum.
func ParseHexColor
func ParseHexColor(s string) (Color, error)
ParseHexColor parses #RRGGBB, RRGGBB, #AARRGGBB, or AARRGGBB into a Color.
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) A
func (c Color) A() uint8
A returns the alpha component as an 8-bit value.
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) B
func (c Color) B() uint8
B returns the blue component as an 8-bit value.
func (Color) G
func (c Color) G() uint8
G returns the green component as an 8-bit value.
func (Color) R
func (c Color) R() uint8
R returns the red component as an 8-bit value.
func (Color) RGBAF
func (c Color) RGBAF() (r, g, b, a float64)
RGBAF returns normalized color components (0.0 to 1.0).
func (Color) RelativeLuminance
func (c Color) RelativeLuminance() float64
RelativeLuminance returns the relative luminance of c per WCAG 2.1. See: https://www.w3.org/WAI/GL/wiki/Relative_luminance
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