paint

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package paint provides 2D drawing primitives built on Cairo.

It wraps the Cairo graphics library with a Go-friendly API for drawing shapes, text, images, and managing colors, fonts, and icons.

Key types:

  • Painter: the main drawing interface (lines, rectangles, arcs, text)
  • Color: RGBA color with named color parsing
  • Font: font family, size, bold/italic
  • Icon: multi-resolution icon with automatic size selection
  • Pixmap: off-screen image surface for rendering
  • Surface: Cairo surface abstraction

Index

Constants

View Source
const (
	FormatInvalid Format = -1
	FormatARGB32         = 0
	FormatRGB24          = 1
)

Variables

View Source
var ColorModel color.Model = color.ModelFunc(colorModel)
View Source
var HSLModel color.Model = color.ModelFunc(hslModel)

Functions

func ClosePainter

func ClosePainter(p Painter)

ClosePainter releases an exclusively owned painter immediately. It does not change Painter's interface, so custom painters remain compatible. The caller must not draw through any aliases afterwards. Close painters before closing their target surfaces; finalizers remain a safety net for old hosts.

func CloseSurface

func CloseSurface(s Surface)

CloseSurface releases an exclusively owned native surface without waiting for Go's heap-driven GC. No interface change is required of custom surfaces. All painters/aliases owned by the caller must be retired first.

func DrawShadowRect

func DrawShadowRect(g Painter, x, y, w, h, radius, blur float64, color Color)

DrawShadowRect renders a soft drop shadow under a (possibly rounded) rectangle by stacking N offset rounded-rect fills with linearly falling alpha. Mirrors glui's `Renderer.FillBoxShadow` shape so the two backends present the same shadow API to host code:

glui:   r.FillBoxShadow(rc, radius, blur, color)
cairo:  paint.DrawShadowRect(g, x, y, w, h, radius, blur, color)

The host should draw the actual rectangle ON TOP of the shadow, not beneath. The shadow does not punch out the centre — for opaque shapes the rect-on-top render order makes the inner overdraw invisible; for translucent shapes, callers either tolerate the overdraw or switch to a stencil-cut primitive (not available on the cairo path).

Algorithm: blur is rounded to N=ceil(blur). We render N+1 layers outset by 0..N points, with alpha falling linearly from color.A at the innermost layer down to color.A/(N+1) at the outermost. The linear ramp approximates a Gaussian closely enough that designers don't notice the difference at typical card-elevation blur values (2–8 points). For a sharper drop shadow pass blur ≤ 2.

Degenerate inputs short-circuit cleanly:

  • blur ≤ 0 → no shadow drawn
  • w/h ≤ 0 → no silhouette
  • color.A = 0 → invisible shadow, skip

func IconTextToPixmap

func IconTextToPixmap(ico Icon, icoSize float64, grayed bool, text string, font Font, textColor Color, border bool) *cairoSurface

func LoadPngFile

func LoadPngFile(filename string) (*cairoSurface, error)

func NewPen

func NewPen(cr Color, width float64) *pen

func NewPixmap

func NewPixmap(w, h int) *cairoSurface

func Round

func Round(x float64) float64

此函数为四舍五入操作 注: 此函数只用于实现"对齐到像素"功能, 不能正确处理nan,inf等非法值

func RunPainterBattery

func RunPainterBattery(t PainterTestingT, p Painter)

RunPainterBattery exercises every method of the paint.Painter interface against `p`, exposing implementations that nil-deref, panic on simple inputs, or silently no-op when given a brush type they don't recognise.

Each Painter implementation in the silk tree (cairo, svgexport, pdfexport, recpaint) gets a four-line conformance test:

func TestPainterBattery(t *testing.T) {
    paint.RunPainterBattery(t, makePainter())
}

The battery is intentionally argumentless beyond the painter — the shapes it draws are arbitrary but cover the full method surface once. If a method panics or warns, the painter implementation gets a t.Errorf with the method name. Otherwise the battery stays silent. There are no rendered-output assertions: image diffs live in the per-painter tests where they have ground-truth fixtures.

Each method is wrapped in a helper that recovers from panics so one broken op doesn't mask the rest.

func SetIconPalette

func SetIconPalette(palette IconPalette)

func SetPreferVectorIcons

func SetPreferVectorIcons(prefer bool)

SetPreferVectorIcons lets an IDE opt into crisp theme-aware built-ins even when an older resource pack supplies low-resolution PNGs for the same names. Custom/unknown resource icons are untouched. Existing Icon references are upgraded in place, including handles loaded during package initialization.

func TextToPixmap

func TextToPixmap(text string, font Font, color Color, border bool) *cairoSurface

Types

type Brush

type Brush interface {
}

type CappedPen

type CappedPen interface {
	Pen
	LineCap() LineCap
	LineJoin() LineJoin
	MiterLimit() float64
}

CappedPen is an optional capability interface for Pens that specify a non-default LineCap or LineJoin.

type Color

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

func ColorFromBgrUint32

func ColorFromBgrUint32(c uint32) Color

func ParseColor

func ParseColor(s string) Color

func (Color) NRGBAf

func (cr Color) NRGBAf() (r, g, b, a float64)

func (Color) RGBA

func (c Color) RGBA() (r, g, b, a uint32)

func (Color) String

func (cr Color) String() string

type DashedPen

type DashedPen interface {
	Pen
	// Dash returns alternating on/off lengths in points. Empty/nil = solid.
	Dash() []float64
	// DashOffset is the initial phase along the pattern (default 0).
	DashOffset() float64
}

DashedPen is an optional capability interface for Pens that carry a dash pattern. Painters can detect dashed pens via type assertion:

if dp, ok := pen.(paint.DashedPen); ok {
    pattern := dp.Dash()
    offset := dp.DashOffset()
}

Pens that don't implement this stroke as solid lines.

type Extend

type Extend int
const (
	ExtNone Extend = iota
	ExtRepeat
	ExtReflect
	ExtPad
)

type Font

type Font interface {
	Family() string
	SetFamily(family string)
	Size() int
	SetSize(sz int)
	Italic() bool
	SetItalic(b bool)
	Bold() bool
	SetBold(b bool)
	Dup() Font
	Equal(f Font) bool
	String() string
	ScaledFont(ctm *geom.Mat3x2) ScaledFont
	FontExtents() *FontExtents
	TextExtents(text string) *TextExtents
	GlyphExtents(glyphs []Glyph) *TextExtents
	TextToGlyphs(x, y float64, text string) []Glyph
}

字体

func NewFont

func NewFont(family string, size int, bold, italic bool) Font

type FontExtents

type FontExtents cairo.FontExtents

type Format

type Format int

type Glyph

type Glyph cairo.Glyph

type GradientStop

type GradientStop struct {
	Offset float32
	Color  Color
}

GradientStop is a single colour stop along a gradient axis.

type HSL

type HSL struct {
	H, S, L, A float64
}

func (HSL) RGBA

func (hsl HSL) RGBA() (r, g, b, a uint32)

type Icon

type Icon interface {
	AvailableSize() []int
	IsAir() bool
	Pixmap(size int) Pixmap
}

func AirIcon

func AirIcon() Icon

func LoadIcon

func LoadIcon(name string) Icon

加载图标 如果加载失败, 则返回"大红叉"图标, 名为"image-missing" 此函数将缓存已加载的图标, 以优化加载效率 更换图标后需要重启才能生效

type IconPalette

type IconPalette struct {
	Foreground, Accent, Success, Warning, Danger, Violet, Paper, Disabled Color
}

IconPalette holds exact, unpremultiplied 8-bit sRGB colors. Hosts switch it on the UI thread with their theme. Resource PNGs keep their original colors; procedural icons (including already-loaded instances) use the current palette.

func CurrentIconPalette

func CurrentIconPalette() IconPalette

func DarkIconPalette

func DarkIconPalette() IconPalette

func LightIconPalette

func LightIconPalette() IconPalette

type LineCap

type LineCap int

LineCap selects how the endpoints of a stroked line are rendered.

const (
	LineCapButt LineCap = iota
	LineCapRound
	LineCapSquare
)

type LineJoin

type LineJoin int

LineJoin selects how connected line segments meet.

const (
	LineJoinMiter LineJoin = iota
	LineJoinBevel
	LineJoinRound
)

type LineStyle

type LineStyle interface {
	Width() float64
}

type LinearGradient

type LinearGradient struct {
	X0, Y0, X1, Y1 float32
	Stops          []GradientStop
	// contains filtered or unexported fields
}

LinearGradient is a brush that interpolates colour along a straight axis.

func NewLinearGradient

func NewLinearGradient(x0, y0, x1, y1 float32) *LinearGradient

func (*LinearGradient) AddStop

func (g *LinearGradient) AddStop(offset float32, c Color)

type Operator

type Operator int
const (
	OpClear Operator = iota

	OpSource
	OpOver
	OpIn
	OpOut
	OpAtop

	OpDest
	OpDestOver
	OpDestIn
	OpDestOut
	OpDestAtop

	OpXor
	OpAdd
	OpSaturate

	OpMultiply
	OpScreen
	OpOverlay
	OpDarken
	OpLighten
	OpColorDodge
	OpColorBurn
	OpHardLigh
	OpSoftLigh
	OpDifference
	OpExclusion
	OpHslHue
	OpHslSaturate
	OpHslColor
	OpHslLuminosity
)

type Painter

type Painter interface {
	Target() Surface

	Save() int
	Restore() int
	RestoreTo(int) bool
	CurrentState() int

	CurrentPoint() (x, y float64)

	Arc(xc, yc, radius, angle1, angle2 float64)
	ArcNegative(xc, yc, radius, angle1, angle2 float64)
	CurveTo(x1, y1, x2, y2, x3, y3 float64)
	Line(x1, y1, x2, y2 float64)
	LineTo(x, y float64)
	MoveTo(x, y float64)
	Rectangle(x, y, width, height float64)
	Rectangle1(rect geom.Rect)

	Stroke()
	StrokePreserve()

	// 填充
	Fill()
	FillPreserve()

	// 在整个剪裁区域内填充
	Paint()
	PaintWithAlpha(alpha uint8)

	ResetClip()
	Clip()
	ClipPreserve()
	ClipBounds() (x, y, width, height float64)
	ClipBounds1() geom.Rect

	SetOperator(op Operator)

	ResetMatrix()
	Translate(tx, ty float64)
	Scale(sx, sy float64)
	Rotate(radians float64)
	Transform(m *geom.Mat3x2)
	SetMatrix(m *geom.Mat3x2)
	GetMatrix(m *geom.Mat3x2)

	SetPen(pen Pen)
	SetPen1(cr Color, width float64)

	SetBrush(br Brush)
	SetBrush1(cr Color)

	SetFont(f Font)
	Font() Font

	ScaledFont() ScaledFont

	DrawText(text string)
	DrawText1(x, y float64, text string)
	DrawGlyphs(glyphs []Glyph)
	DrawGlyph(glyph *Glyph)

	DrawPixmap(pixmap Pixmap)
	DrawPixmap1(x, y float64, pixmap Pixmap)
	DrawPixmap2(x, y float64, pixmap Pixmap, x0, y0 float64)
	DrawPixmap5(x, y, w, h float64, pixmap Pixmap)

	DrawIcon(ico Icon, fSize float64, grayed bool)
	DrawIcon1(ico Icon, x, y, fSize float64, grayed bool)
}

type PainterTestingT

type PainterTestingT interface {
	Helper()
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

PainterTestingT is the trim TestingT subset RunPainterBattery uses, matching the standard library's testing.TB methods we actually call. Lives here so the paint package doesn't take a hard testing import — the battery can be driven from any harness that supplies the same three methods.

type Pen

type Pen interface {
	Width() float64
	Color() Color
}

考虑到兼容性, 我们的画笔只支持纯色, 不支持图案填充

func NewStyledPen

func NewStyledPen(color Color, width float64, dash []float64,
	dashOffset float64, lineCap LineCap, lineJoin LineJoin) Pen

NewStyledPen returns a Pen that carries dash, cap, and join info.

type Pixmap

type Pixmap interface {
	Surface
	Format() Format
	Width() int
	Height() int
	Stride() int
	DataPtr() unsafe.Pointer
	WritePNGToStream(w io.Writer) error
	WritePNG(filename string) error
	Image() (image.Image, error)
	SetData(src []uint8) error
	SetImage(img image.Image) error
}

type PixmapBrush

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

func NewPixmapBrush

func NewPixmapBrush(pixmap Pixmap) *PixmapBrush

func (*PixmapBrush) Extend

func (this *PixmapBrush) Extend() Extend

func (*PixmapBrush) SetExtend

func (this *PixmapBrush) SetExtend(ext Extend)

type RadialGradient

type RadialGradient struct {
	Cx, Cy, R0, R1 float32
	Stops          []GradientStop
	// contains filtered or unexported fields
}

RadialGradient mirrors LinearGradient but radiates from a centre.

func NewRadialGradient

func NewRadialGradient(cx, cy, r0, r1 float32) *RadialGradient

func (*RadialGradient) AddStop

func (g *RadialGradient) AddStop(offset float32, c Color)

type RichPen

type RichPen interface {
	DashedPen
	CappedPen
}

RichPen is the union of all extension interfaces — most concrete rich pen implementations satisfy this for one-shot type assertion.

type ScaledFont

type ScaledFont interface {
	Font() Font
	FontExtents() *FontExtents
	TextExtents(text string) *TextExtents
	GlyphExtents(glyphs []Glyph) *TextExtents
	TextToGlyphs(x, y float64, text string) []Glyph
}

type SolidBrush

type SolidBrush struct {
	Color Color
}

func NewSolidBrush

func NewSolidBrush(cr Color) *SolidBrush

type Surface

type Surface interface {
	SurfaceType() cairo.SurfaceType
	NewPainter() Painter
	// NewSimilar(w, h int, color, alpha bool) Pixmap  // should be NewSimilarPixmap
	Flush()
}

type TextExtents

type TextExtents cairo.TextExtents

Jump to

Keyboard shortcuts

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