paint
分层
只有 api/stable/ui_paint.txt 列出的符号受兼容性承诺约束。标有「实验性」的符号,以及类型下「实验性成员」列出的字段,任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。
import "github.com/tangoui/tango/ui/paint"本页由
site/tools/apigen从源码注释生成(按 darwin 构建标签选文件),请勿手改。
Package paint is the display-list layer of the Tango self-drawn UI.
Components record drawing commands (rounded rectangles, borders, Ant-style layered box shadows, paths, gradients, checkerboards, images, glyph runs, clips, opacity groups, affine transform groups and backdrop blurs) into a List in logical pixels. A Renderer turns the list into pixels; this package ships a pure-Go CPU rasterizer (CPU, built on x/image/vector) that writes an *image.RGBA at any device scale. The List is deliberately a flat, backend-neutral value so a GPU renderer can consume the same commands later without changes to components.
API tiers: only the symbols listed in api/stable/ui_paint.txt are covered by the compatibility promise of docs/release.md ("API 稳定性"); every other exported symbol is Experimental and may change in any 0.x release. The API reference on the documentation site marks the experimental symbols.
常量
const (
// MaxBlurTaps is the largest BlurPlan.Taps (the GPU shader loops over
// at most 2·MaxBlurTaps+1 taps).
MaxBlurTaps = 24
// MaxBlurDown is the largest BlurPlan.Down.
MaxBlurDown = maxBlurDown
)实验性
const MaxBackdropBlur = 64MaxBackdropBlur is the largest BackdropBlur.Radius (logical pixels); larger radii are clamped to it.
实验性
const RampWidth = 256RampWidth is the number of entries of a gradient color ramp: one per t = i/255, i = 0..255.
实验性
变量
var (
CheckerLight = color.NRGBA{0xff, 0xff, 0xff, 0xff}
CheckerDark = color.NRGBA{0xe6, 0xe6, 0xe6, 0xff}
)Default checkerboard colors (used when Checker.A and B are both zero).
实验性
var ErrImageFormat = errors.New("paint: unsupported image format (want PNG or JPEG)")ErrImageFormat is returned by DecodeImage for data that is neither PNG nor JPEG.
实验性
函数
func BackdropBlurReach 实验性
func BackdropBlurReach(radius, scale float32) float32BackdropBlurReach returns how far, in logical pixels, a BackdropBlur of radius at scale reads beyond its rectangle (its source margin, plus a pixel for rounding): a change within that distance changes its pixels.
func BlurSigma 实验性
func BlurSigma(radius, scale float32) float32BlurSigma returns the device sigma of a BackdropBlur of radius at scale: min(radius, MaxBackdropBlur)·scale, at most 256; 0 when nothing is blurred (radius <= 0 or NaN).
func CatmullRomWeights 实验性
func CatmullRomWeights(f float32) [4]float32CatmullRomWeights returns the weights of the four texels around a sample point whose fractional position past the second texel's center is f (0 ≤ f < 1): the Catmull-Rom cubic (Mitchell–Netravali B = 0, C = 0.5),
w0 = -0.5f³ + f² - 0.5f
w1 = 1.5f³ - 2.5f² + 1
w2 = -1.5f³ + 2f² + 0.5f
w3 = 0.5f³ - 0.5f²
They sum to 1 and give (0, 1, 0, 0) at f = 0, so texel centers sample exactly. shaders.CatmullRomWeights is the same.
func CheckerColors 实验性
func CheckerColors(o Checker) (a, b color.NRGBA)CheckerColors returns the two colors o draws: A and B, or CheckerLight and CheckerDark when both are zero.
func CheckerSelect 实验性
func CheckerSelect(p, anchor geom.Point, cell float32) float32CheckerSelect is the checkerboard color of the pixel centered at p for cells of size cell whose grid starts at anchor: 0 for the anchor cell's color (Checker.A) and every cell an even number of steps away, 1 for the others. It is shaders.CheckerSelect's formula.
func DecodeImage 实验性
func DecodeImage(r io.Reader) (image.Image, error)DecodeImage decodes a PNG or JPEG stream (sniffed from its signature) with the standard library decoders.
func Dither4x4 实验性
func Dither4x4(x, y int) float32Dither4x4 is the 4×4 Bayer ordered-dither threshold of device pixel (x, y), in (0, 1): (B+0.5)/16 for the Bayer index B in 0..15. Both renderers dither gradients with it (DitherPremul); shaders.Dither4x4 is the same table (a test keeps them equal).
func DitherPremul 实验性
func DitherPremul(c [4]float32, d float32) [4]float32DitherPremul offsets the color channels of the premultiplied color c (0..1) by (d-0.5)/255 for the dither threshold d, clamped to 0..alpha, so that rounding the result to 8 bits spreads a gradient's sub-level values over neighbouring pixels instead of leaving visible bands. Alpha is not dithered; a color exactly on an 8-bit level stays on it (the offset is below half a level). shaders.DitherPremul is the same.
func GlyphPlacement 实验性
func GlyphPlacement(origin geom.Point, g Glyph, scale float32) (ix, iy int, sub uint8)GlyphPlacement returns the device pen position of glyph g of a Text op at origin: x is floored to whole pixels with the remainder bucketed into quarter pixels (sub, 0..3), y is rounded. Render places glyphs with it.
func GradientDrawable 实验性
func GradientDrawable(g Gradient) boolGradientDrawable reports whether g draws anything (see gradientDrawable); the GPU renderer drops the gradients paint.CPU drops.
func GradientRamp 实验性
func GradientRamp(stops []Stop) [RampWidth]color.NRGBA64GradientRamp evaluates stops at t = i/255 for every ramp entry i. Colors are interpolated linearly in non-premultiplied sRGB (alpha included), as CSS does, and kept at 16 bits per channel (an 8-bit stop channel v is v*257): a ramp of 8-bit entries would be a staircase for gradients spanning few levels (#f0f2f5→#e6e8eb changes by one level every 25 entries), leaving the ordered dither (Dither4x4) nothing between levels to spread. Before the first stop the ramp holds the first stop's color and after the last the last's. Stops are stably sorted by Offset first (a copy; stops is not modified), so unsorted stops work and stops sharing an Offset keep their order: two stops at one offset are a hard edge, the earlier one's color holding at exactly that offset. A stop with a NaN Offset is ignored and ±Inf offsets count as 1 / 0. No (usable) stops is transparent.
Both renderers draw gradients through this ramp: paint.CPU samples it with RampSample, the GPU renderer uploads it (premultiplied, RampPremul) as a row of its ramp texture.
func GradientT 实验性
func GradientT(kind GradientKind, p, start, end geom.Point) float32GradientT is the gradient parameter (offset 0 at Start, 1 at the end) of the point p. It is shaders.GradientT's formula, operation by operation (a test keeps them equal):
- GradientLinear (and unknown kinds): the projection of p - Start onto End - Start, divided by its squared length (0 everywhere when Start == End).
- GradientRadial: |p - Start| / |End - Start| (radius 1 when Start == End).
- GradientConic: the angle from the direction End - Start (+x when Start == End) to p - Start, clockwise on screen (y down), in turns, in [0, 1). The arctangent is the Abramowitz–Stegun 4.4.49 polynomial (error below 1e-5 rad), the same on every backend.
The result is not clamped; RampSample clamps it.
func ImageAligned 实验性
func ImageAligned(dr geom.Rect, size image.Point) boolImageAligned reports whether an image of size texels drawn on the device rectangle dr maps its texels one to one onto device pixels: dr is at a whole device pixel and has the same positive size as the image. Every device pixel center is then a texel center, where the Catmull-Rom filter's weights on each axis are 0, 1, 0, 0.
func ImageDrawable 实验性
func ImageDrawable(o Image) boolImageDrawable reports whether o draws anything: a non-nil image with pixels in a rectangle of positive, finite size at a finite position.
func ImageReduction 实验性
func ImageReduction(b image.Rectangle, devW, devH float32) (w, h int)ImageReduction returns the size an image with bounds b is first reduced to (with an area-averaging box filter, PrepareImage) before it is drawn devW×devH device pixels large, or 0, 0 when it is drawn from its full resolution. Each axis is reduced on its own: one more than twice the drawn size becomes ceil(drawn size), the other keeps the source size (so 4000×100 drawn 100×100 is reduced to 100×100, 4000×100 drawn 100×80 to 100×100). Without it the 4×4 Catmull-Rom filter would skip source texels and alias. Both renderers prepare images this way, so they sample the same texels.
func ImageTexelF 实验性
func ImageTexelF(src *image.RGBA, x, y float32) [4]float32ImageTexelF is SampleCatmullRomF of an aligned image (ImageAligned) at the device pixel whose center is (x, y) from the image's corner: the texel there, with edge and premultiplied color clamping. An empty image samples transparent.
func Orient 实验性
func Orient(src image.Image, quarter int, flipX, flipY bool) *image.RGBAOrient mirrors src (flipX horizontally, flipY vertically) and then rotates it by quarter turns clockwise (negative = counter-clockwise), losslessly. With nothing to do it returns ToRGBA(src).
func PathDeviceBounds 实验性
func PathDeviceBounds(p *Path, scale float32) image.RectanglePathDeviceBounds returns the device pixels FillPath of p may touch at scale: p's bounds scaled, floored / ceiled to whole pixels and grown by one pixel on each side (the rectangle paint.CPU rasterizes FillPath in; its outermost rows and columns are always transparent). Coordinates beyond ±2^24 pixels are clamped.
func PrepareImage 实验性
func PrepareImage(src image.Image, w, h int) *image.RGBAPrepareImage returns the premultiplied, origin-anchored pixels an image is sampled from: ToRGBA(src) (src itself when it already is such an *image.RGBA), reduced to w×h when w > 0 (ImageReduction's result) by averaging, per output texel, the source area it covers (a separable box filter with fractional edge weights; an axis whose size does not change is copied).
func RRectCoverage 实验性
func RRectCoverage(px, py float32, r geom.Rect, radii geom.Radii) float32RRectCoverage returns how much of the pixel centered at (px, py) the rounded rectangle r with corner radii radii covers, in 0..1. All values are in the same (device) units.
It is the single coverage definition shared by paint.CPU and the GPU quad shader (internal/render/gpu/shaders.RRectCoverage computes exactly the same float32 formula; a test keeps them equal):
- Away from rounded corners it is the exact area overlap of the unit pixel square with the rectangle (covX*covY).
- When the pixel center lies in a rounded corner's quadrant (within r of both edges meeting there, r > 0) it is Clamp(0.5 - sdf, 0, 1), sdf being the signed distance to the rounded boundary (negative inside), capped by the box overlap.
Radii are clamped to half the shorter side (as geom.Radii.Clamp does); an empty rectangle covers nothing.
func RampPremul 实验性
func RampPremul(ramp *[RampWidth]color.NRGBA64) [RampWidth * 4]uint16RampPremul converts ramp to the row both renderers sample: RampWidth premultiplied RGBA texels of 16-bit unsigned normalized channels (the GPU's RGBA16Unorm ramp texture), each rounded to nearest.
func RampSample 实验性
func RampSample(row *[RampWidth * 4]uint16, t float32) [4]float32RampSample returns the premultiplied color (0..1) of the ramp row at gradient parameter t, exactly as the GPU's linear-filtered sample of the row at u = RampU(t) computes it (shaders.RampU and sl.Texture2D's bilinear filter): t is clamped to 0..1 (NaN is 0), then entry floor(t*255) and the next are interpolated by the fraction.
func Resample 实验性
func Resample(src image.Image, sx, sy, sw, sh float64, w, h int) *image.RGBAResample maps the source rectangle (sx, sy, sw, sh), in pixels of src's bounds relative to its top-left corner, onto a new w×h image with bilinear filtering (pixel centres aligned, edges clamped, large reductions prefiltered like ResizeBilinear). It crops and scales in one pass, e.g. for "cover" image fitting.
func ResizeBilinear 实验性
func ResizeBilinear(src image.Image, w, h int) *image.RGBAResizeBilinear scales src to w×h with bilinear interpolation. Large reductions first halve the source with a 2×2 box filter so that every source pixel contributes (no aliasing).
func SampleCatmullRom 实验性
func SampleCatmullRom(src *image.RGBA, u, v float32) color.RGBASampleCatmullRom is SampleCatmullRomF rounded to 8-bit premultiplied color.
func SampleCatmullRomF 实验性
func SampleCatmullRomF(src *image.RGBA, u, v float32) [4]float32SampleCatmullRomF samples the premultiplied image src at the normalized position (u, v) (0..1 spans src's bounds; texel (i, j) is centered at ((i+0.5)/w, (j+0.5)/h)) with the Catmull-Rom filter over the 4×4 texels around it, edges clamped (texels outside src repeat the border). The cubic's negative lobes can overshoot, so the result is clamped to valid premultiplied color: alpha to 0..1, then each color channel to 0..alpha. The channels are 0..1.
The arithmetic is shaders.SampleCatmullRom's, step by step: the texel coordinate x = u*w - 0.5 splits into x0 = floor(x) and the fraction; the four rows y0-1 … y0+2 are each filtered horizontally (texels x0-1 … x0+2, weighted left to right) and the rows are then weighted top to bottom. src's 8-bit channels read as v/255, which is what the GPU's RGBA8Unorm texture returns. An empty src samples transparent.
func ShadowCoverage 实验性
func ShadowCoverage(px, py float32, r geom.Rect, radii geom.Radii, sigma float32) float32ShadowCoverage returns how much of the pixel centered at (px, py) a box shadow covers, in 0..1: the rounded rectangle r (corner radii radii) blurred by a Gaussian of standard deviation sigma. All values are in the same (device) units; ShadowRect uses sigma = Blur*scale/2, with Spread already applied to r and radii.
It is the single shadow definition shared by paint.CPU and the GPU quad shader (internal/render/gpu/shaders.ShadowCoverage computes exactly the same float32 formula; a test keeps them equal), a closed-form approximation of the true Gaussian blur (within 0.02 of it for sigma >= 0.25):
- The pixel's box filter is folded into the blur as a Gaussian of variance 1/12: s = sqrt(sigma² + 1/12), so sigma 0 is an anti-aliased rounded rectangle (a negative or NaN sigma counts as 0).
- The square-cornered rectangle's blurred coverage is exact and separable: the product over both axes of the Gaussian mass between the two edges, 0.5·(erf((p-lo)/(s√2)) - erf((p-hi)/(s√2))).
- Each rounded corner (radius clamped to half the shorter side, as in RRectCoverage) subtracts the Gaussian mass of the region it cuts off the square corner: the corner's rows within 3s of the pixel are cut into 4 strips, each strip's mass along the rows is exact and multiplies the mass across the row between the edge and the arc at the strip's middle. The region is symmetric about the corner's diagonal, so the strips run along whichever edge keeps them off the arc's steep end.
erf is Abramowitz–Stegun 7.1.26 (sl.Erf; absolute error ≤ 1.5e-7). An empty r covers nothing.
func StrokeCoverage 实验性
func StrokeCoverage(px, py float32, r geom.Rect, radii geom.Radii, width float32, dash []float32, dashPhase float32) float32StrokeCoverage returns how much of the pixel centered at (px, py) a StrokeRect border covers, in 0..1: a border of the given width inside the rounded rectangle r (corner radii radii), dashed with dash starting at dashPhase. All values are in the same (device) units.
It is the single stroke definition shared by paint.CPU and the GPU quad shader (internal/render/gpu/shaders.StrokeCoverage computes exactly the same float32 formula; a test keeps them equal):
- The ring is RRectCoverage(r, radii) minus the RRectCoverage of r inset by width with every radius reduced by width (not below 0), clamped to 0..1 — the border StrokeRect always drew (CSS border-box). A width of at least half the shorter side fills r; a width <= 0 (or NaN) or an empty r draws nothing.
- The dash is evaluated at the pixel's arc length along the stroke centerline (r inset by half the width, radii reduced by as much and clamped to it) plus dashPhase. Arc length 0 is where the top-left corner ends on the top edge, and it grows clockwise; on a rounded corner it is measured along the centerline's circular arc. Pixels map to a corner's arc beyond its center along both axes, elsewhere to the nearer edge. Dash ends are anti-aliased over one pixel of arc length.
- dash holds alternating on/off lengths. Only the first 4 entries are used (the GPU carries 4; longer patterns are truncated), and the first entry <= 0 (or NaN) ends the pattern. An empty pattern is solid. An odd count repeats the pattern twice as in SVG ({a} is on a, off a). A period shorter than one pixel draws its average coverage.
Where the outline closes (the top-left corner) the pattern restarts, as a dash along a path does.
func ToRGBA 实验性
func ToRGBA(src image.Image) *image.RGBAToRGBA returns src as a premultiplied *image.RGBA anchored at 0,0. An *image.RGBA that already starts at the origin is returned as is (not copied); interpolating premultiplied values avoids dark alpha fringes.
类型
BackdropBlur 实验性
type BackdropBlur struct {
Rect geom.Rect
Radii geom.Radii
Radius float32
}BackdropBlur blurs what is already drawn under a rounded rectangle (CSS backdrop-filter: blur()): the pixels of the current target — the window, or inside a PushOpacity group that group's own layer — inside Rect (rounded by Radii, clipped by the active clips) are replaced by a Gaussian blur of the target as drawn so far, and every later op draws over the blurred result. A frosted surface is a BackdropBlur followed by a translucent FillRect of the same shape.
Radius is the Gaussian's standard deviation in logical pixels (CSS blur()), scaled like any length by the device scale and a uniform PushTransform; it is clamped to MaxBackdropBlur, and a Radius <= 0 (or NaN) draws nothing. The blur reads up to BackdropBlurReach beyond Rect; pixels beyond the window's edges repeat its edge pixels, pixels a group's layer holds nothing at are transparent. The blurred copy is composited source-over through the rectangle's coverage: where the target is opaque this replaces its pixels, where it is translucent (in a group) the unblurred pixels show through by the copy's transparency.
Both renderers compute the same blur (PlanBackdropBlur; see blur.go for the algorithm and its cost). Under a transform that rotates, skews, mirrors one axis or scales non-uniformly the op draws nothing.
Redraw hints: a BackdropBlur's pixels depend on everything drawn under it within its reach. Renderers that redraw partially (the GPU renderer) redraw the whole blurred region with its source whenever a hinted change or scroll touches it; the ui Runner damages the region likewise (see ui/damage.go). Code that records Damage hints itself must not rely on a ScrollRegion carrying blurred pixels along.
BlurPlan 实验性
type BlurPlan struct {
Out image.Rectangle // pixels the blur may change
Src image.Rectangle // pixels it reads (inside the frame)
Down int // downsampling factor, a power of two
Sigma float32 // Gaussian sigma in reduced texels
Taps int // kernel half width in reduced texels
Small image.Point // reduced image size: Src.Size()/Down rounded up
}BlurPlan is the device-pixel plan of one BackdropBlur (see the top of blur.go): paint.CPU and the GPU renderer run the same plan.
func PlanBackdropBlur 实验性
func PlanBackdropBlur(dr geom.Rect, sigma float32, clip, frame image.Rectangle) (p BlurPlan, ok bool)PlanBackdropBlur plans a blur of device sigma sigma (BlurSigma) over the device rectangle dr, within the clip rectangle clip, in a frame of device pixels frame. ok is false when it changes nothing (no sigma, non-finite or empty rectangle, nothing inside the clip and frame).
CPU 实验性
type CPU struct {
// TextGamma < 1 thickens glyph coverage slightly (closer to native
// rasterizers). 1 is linear coverage.
TextGamma float64
// contains filtered or unexported fields
}CPU is the pure-Go reference renderer. It is not safe for concurrent use.
func NewCPU 实验性
func NewCPU() *CPUNewCPU returns a CPU renderer.
func (*CPU) BeginFrame 实验性
func (r *CPU) BeginFrame(scale float32)BeginFrame starts a frame for a caller that draws through RenderRegion and GlyphMask instead of Render (GPU renderers): it sets the device scale (dropping the scale-dependent caches when it changes) and counts one frame for evicting cached glyphs and images, as each Render call does. Call it once per frame, before the frame's RenderRegion and GlyphMask calls.
func (*CPU) GlyphMask 实验性
func (r *CPU) GlyphMask(g Glyph, deviceSize float32, sub uint8) (mask *image.Alpha, off image.Point)GlyphMask returns the coverage mask of g rasterized at deviceSize pixels with sub-pixel x bucket sub (0..3, quarter pixels; see GlyphPlacement), with TextGamma applied (a GlyphRasterizer source supplies its own mask, gamma included), exactly as Render draws it. off is the mask's top-left relative to the device pen position. A nil mask means the glyph is empty (space) or too large. Masks are cached and shared: do not modify.
func (*CPU) Image 实验性
func (r *CPU) Image() *image.RGBAImage returns the last rendered frame (device pixels).
func (*CPU) InvalidateImage 实验性
func (r *CPU) InvalidateImage(img image.Image)InvalidateImage drops the prepared pixels cached for img (by its image.Image value), so the next frame drawing it reads its current pixels: call it after changing an image's pixels in place.
func (*CPU) PathMask 实验性
func (r *CPU) PathMask(p *Path) (mask *image.Alpha, at image.Point)PathMask returns the coverage of p (logical coordinates, non-zero rule) at the device scale of the current frame (BeginFrame) as an 8-bit mask with origin 0,0 covering PathDeviceBounds(p, scale), placed at at: the coverage paint.CPU draws FillPath and Path-shaped gradients with. GPU renderers cache it to draw FillPath without a patch. The caller must keep the mask small: it allocates the whole bounds.
func (*CPU) Render 实验性
func (r *CPU) Render(l *List, size geom.Size, scale float32) errorRender rasterizes l into an internal RGBA of ceil(size*scale) pixels.
func (*CPU) RenderRegion 实验性
func (r *CPU) RenderRegion(ops []Op, region image.Rectangle, scale float32) *image.RGBARenderRegion draws only ops onto a transparent image whose Bounds() is region (device pixels). Op coordinates stay absolute logical coordinates, so the result equals the region of a full Render of the same ops on a transparent background. Unbalanced Push ops are closed at the end and extra Pops are ignored, as in Render. It does not change Image().
GPU renderers use it to rasterize the commands they do not draw natively (strokes, shadows, paths, gradients, images, opacity groups) as patches. It does not count as a frame for cache eviction: call BeginFrame once per frame, so the patches of one frame do not age each other's glyphs.
func (*CPU) RenderRegionInto 实验性
func (r *CPU) RenderRegionInto(dst *image.RGBA, ops []Op, region image.Rectangle, scale float32) *image.RGBARenderRegionInto is RenderRegion drawing into dst when dst's bounds are exactly region: dst is cleared and reused, so a caller that redraws the same region every frame does not allocate a new raster each time. A nil dst or one of other bounds gets a fresh image, as RenderRegion does.
func (*CPU) Trim 实验性
func (r *CPU) Trim()Trim releases rebuildable glyph, transformed-image and shadow caches. The currently rendered image, scale and text gamma are preserved, so the window can continue presenting it until the next frame. Call between frames on the rendering goroutine. Masks are recomputed with identical pixels on demand.
Cap
type Cap uint8Cap is a stroke end style.
Append-only: never reorder or insert; the zero value stays CapButt.
const (
CapButt Cap = iota
CapRound
CapSquare
)Checker
type Checker struct {
Rect geom.Rect
Radii geom.Radii
Cell float32
A, B color.NRGBA
}Checker fills a rounded rect with a two-color checkerboard (the usual "transparent" background behind color swatches). Cells are Cell logical pixels square, anchored at Rect's top-left corner which gets color A.
Damage 实验性
type Damage struct{ Rect geom.Rect }Damage is a redraw hint, not a drawing command: Rect is a region whose pixels changed since the previous frame. Rect is in the logical coordinates of the place it is recorded, i.e. it goes through the enclosing PushTransform stack like geometry does (clips and opacity groups do not affect it); hints recorded by the ui Runner at the end of a frame are therefore in window logical pixels.
A frame that carries no Damage and no ScrollRegion must be redrawn completely; once a frame carries any hint, everything that changed is covered by the union of its Damage rects and ScrollRegions. Renderers that do not do partial redraws ignore both ops (paint.CPU does; the GPU renderer in internal/render/gpu redraws only the hinted region when its device keeps the previous frame).
FillPath
type FillPath struct {
Path *Path
Color color.NRGBA
}FillPath fills an arbitrary path (non-zero rule). Renderers may cache the path's rasterized coverage by *Path pointer (the GPU renderer does, also for a Gradient's Path): the content of a *Path must not change once it is drawn; to draw a different shape, use a new Path.
FillRect
type FillRect struct {
Rect geom.Rect
Radii geom.Radii
Color color.NRGBA
}FillRect fills a rounded rectangle.
Glyph 实验性
type Glyph struct {
Src GlyphSource
ID uint32
Size float32 // pixel size (logical)
X, Y float32 // relative to the Text op origin
// Skew slants the outline (synthetic italic): x += Skew * height above
// the baseline. 0 draws upright; ~0.2 matches common obliques.
Skew float32
}Glyph is a positioned glyph, origin on the baseline.
GlyphRasterizer 实验性
type GlyphRasterizer interface {
RasterGlyph(id uint32, size float32, subx uint8, skew float32) (mask *image.Alpha, off image.Point, ok bool)
}GlyphRasterizer is an optional interface of a GlyphSource backed by a platform text engine (CoreText, DirectWrite, FreeType) that rasterizes glyphs itself, with the platform's hinting and filtering, instead of letting paint fill the GlyphPath outline.
When the Src of a glyph implements it, CPU.GlyphMask (and so Render and the GPU glyph atlas, which takes its masks from GlyphMask) uses the RasterGlyph result; ok=false falls back to rasterizing GlyphPath.
Contract:
- size is the device pixel size, subx the quarter-pixel x bucket (0..3, see GlyphPlacement) to add to the pen, skew the synthetic italic slant of Glyph.Skew (x += skew * height above the baseline).
- mask is the final 8-bit coverage (R8): the engine applies its own gamma / contrast, so GlyphMask does NOT apply CPU.TextGamma to it. off is the mask's top-left relative to the device pen position (x floored, baseline y rounded, as GlyphPlacement places it). A nil mask with ok=true is an empty glyph (space). Like outline masks, the mask keeps a 1px transparent border, the convention outline masks and the GPU atlas share (the atlas samples nearest, clamps the sample point to within half a texel of the entry's edge and keeps a 1-texel gap between entries); GlyphMask adds the border, moving off by -1,-1, when the source returns a mask inked to its edge.
- The mask is cached and shared by the caller (CPU glyph cache, GPU atlas): the source must not modify it afterwards.
- The result must be a deterministic function of the arguments for a given source. The GPU atlas keys masks by (Src, ID, Size, Sub, Skew) whichever path produced them, and the CPU cache may evict and rebuild a mask while the atlas still holds the old one, so one source must always take the same path for the same key: ok=false only for a glyph the engine really cannot rasterize, and then for that key every time. A source never switches engines at run time; switching engines means new GlyphSource values (a different Src).
- It must be safe for concurrent use.
GlyphSource 实验性
type GlyphSource interface {
// GlyphPath returns the outline of glyph id at the given pixel size with
// its origin on the baseline and y growing downwards. It may return nil
// for empty glyphs (spaces). Implementations should cache.
GlyphPath(id uint32, size float32) *Path
}GlyphSource provides glyph outlines. The text package implements it; paint never imports text so renderers stay independent of shaping.
Gradient
type Gradient struct {
Kind GradientKind
Rect geom.Rect
Radii geom.Radii
Path *Path // optional shape; overrides Rect/Radii; immutable once drawn (see FillPath)
Start, End geom.Point
Stops []Stop
}Gradient fills a rounded rect (or Path, when set) with a multi-stop gradient. Stops are stably sorted by Offset (two stops at one offset are a hard edge); colors are interpolated in non-premultiplied sRGB like CSS and clamped beyond the first/last stop (see GradientRamp). A stop with a NaN Offset is ignored; ±Inf offsets count as 1 / 0.
Both renderers draw through a ramp of RampWidth entries at t = i/255, filtered linearly between entries, so a hard edge (or any two stops closer than 1/255) is not perfectly sharp: it resolves to a transition 1/255 of the gradient's length wide (on a 255 px long gradient, one pixel).
GradientKind
type GradientKind uint8GradientKind selects the gradient geometry.
Append-only: never reorder or insert; the zero value stays GradientLinear.
const (
// GradientLinear runs from Start (offset 0) to End (offset 1).
GradientLinear GradientKind = iota
// GradientRadial is centred on Start; End lies on the offset-1 circle.
GradientRadial
// GradientConic sweeps clockwise around Start beginning in the
// direction of End (offset 0) and ending there after a full turn.
GradientConic
)Image
type Image struct {
Img image.Image
Rect geom.Rect
Radii geom.Radii
}Image draws img scaled into Rect, optionally clipped to rounded corners.
Both renderers sample the image with the same Catmull-Rom filter (SampleCatmullRomF, premultiplied, edges clamped) at device pixel centers; a source more than twice the drawn size on both axes is first reduced to the drawn size (ImageReduction, PrepareImage). Images are cached by their image.Image value (the pointer for the usual pointer types): after changing an image's pixels in place, call the renderer's InvalidateImage (paint.CPU.InvalidateImage, gpu.Renderer.InvalidateImage) or draw a new image value.
LinearGradient
type LinearGradient struct {
Rect geom.Rect
Radii geom.Radii
P0, P1 geom.Point
From, To color.NRGBA
}LinearGradient fills a rounded rect with a two-stop gradient from From (at P0) to To (at P1).
List
type List struct {
Ops []Op
// Background clears the target before drawing (zero = transparent).
Background color.NRGBA
// IconNote, when set, is called by the icon package for every icon
// drawn into the list: its name, whether it is directional (mirrors in
// right-to-left layouts), whether this draw mirrored it, and the square
// it was drawn into (in the list's coordinates at that point). Only
// tools and tests set it (the RTL mirror check, the accessibility
// audit); renderers ignore it. It belongs to the list, so parallel
// tests do not see each other's icons. Reset keeps it.
IconNote func(name string, directional, mirrored bool, r geom.Rect)
// IconStyle is the icon style (a *icon.Style) the icon package applies
// to icons drawn into the list: the theme's replacement icons and
// stroke width. The ui runner sets it from the theme of the scope
// being painted; renderers ignore it. Reset keeps it.
IconStyle any
}List is a recorded frame.
只有部分成员是稳定的:未标「实验性」的方法和下列以外的字段受兼容性承诺约束。
实验性 实验性成员:Ops、IconNote、IconStyle
func (*List) Add
func (l *List) Add(op Op)Add appends a raw op. Add ops by value (l.Add(FillRect{…})), not by pointer: paint.CPU skips pointer ops (the GPU renderer dereferences them).
func (*List) BackdropBlur 实验性
func (l *List) BackdropBlur(r geom.Rect, rad geom.Radii, radius float32)BackdropBlur blurs the pixels already drawn under the rounded rect r with a Gaussian of standard deviation radius (logical pixels; see BackdropBlur). Empty rects and radii <= 0 are dropped.
func (*List) Checker
func (l *List) Checker(r geom.Rect, rad geom.Radii, cell float32, a, b color.NRGBA)Checker fills r with a checkerboard of cell-sized squares. Zero colors use CheckerLight / CheckerDark.
func (*List) Clip
func (l *List) Clip(r geom.Rect, rad geom.Radii)Clip pushes a clip; pair with Pop.
func (*List) Damage 实验性
func (l *List) Damage(r geom.Rect)Damage records a redraw hint for r (see Damage). Empty rects are dropped.
func (*List) DrawImage
func (l *List) DrawImage(img image.Image, r geom.Rect, rad geom.Radii)DrawImage draws img into r.
func (*List) Fill
func (l *List) Fill(r geom.Rect, rad geom.Radii, c color.NRGBA)Fill fills a rounded rect. Fully transparent colors are dropped.
func (*List) Glyphs 实验性
func (l *List) Glyphs(origin geom.Point, g []Glyph, c color.NRGBA)Glyphs draws a glyph run at origin.
func (*List) Gradient
func (l *List) Gradient(g Gradient)Gradient fills with a multi-stop gradient (see Gradient).
func (*List) Line
func (l *List) Line(a, b geom.Point, w float32, c color.NRGBA)Line draws a straight line of width w.
func (*List) LinearStops
func (l *List) LinearStops(r geom.Rect, rad geom.Radii, p0, p1 geom.Point, stops ...Stop)LinearStops fills r with a linear gradient from p0 to p1 through stops.
func (*List) Opacity
func (l *List) Opacity(a float32)Opacity pushes an opacity group; pair with Pop.
func (*List) Path
func (l *List) Path(p *Path, c color.NRGBA)Path fills p.
func (*List) Pop
func (l *List) Pop()Pop closes the innermost group.
func (*List) Reset
func (l *List) Reset()Reset empties the list for reuse.
func (*List) Scroll 实验性
func (l *List) Scroll(r geom.Rect, d geom.Point)Scroll records that the pixels inside r moved by d (see ScrollRegion). Empty rects and zero deltas are dropped.
func (*List) Shadows
func (l *List) Shadows(r geom.Rect, rad geom.Radii, s []Shadow)Shadows draws layered box shadows (in CSS order: first is on top, so they are recorded back to front).
func (*List) Stroke
func (l *List) Stroke(r geom.Rect, rad geom.Radii, w float32, c color.NRGBA)Stroke draws a border of width w inside r.
func (*List) StrokeDashed
func (l *List) StrokeDashed(r geom.Rect, rad geom.Radii, w float32, c color.NRGBA, dash []float32)StrokeDashed draws a dashed border.
func (*List) StrokePath
func (l *List) StrokePath(p *Path, st StrokeStyle, c color.NRGBA)StrokePath strokes p.
func (*List) Transform
func (l *List) Transform(m geom.Affine)Transform pushes an affine transform group; pair with Pop. See geom.Translate, geom.Scale, geom.Rotate, geom.ScaleAround and geom.RotateAround for the usual constructors.
Op
type Op interface {
// contains filtered or unexported methods
}Op is any display-list command.
Path
type Path struct {
Segs []Seg
// contains filtered or unexported fields
}Path is a resolution-independent outline in logical pixels.
func MustSVGPath
func MustSVGPath(d string) *PathMustSVGPath is ParseSVGPath that panics; for literal icon data.
func NewPath
func NewPath() *PathNewPath returns an empty path.
func ParseSVGPath
func ParseSVGPath(d string) (*Path, error)ParseSVGPath parses SVG path data ("M3 12h18", arcs included) into a Path.
func StrokeToFill
func StrokeToFill(p *Path, st StrokeStyle) *PathStrokeToFill converts a stroked path into a fillable path whose polygons all share one orientation, so the non-zero rule unions them.
func (*Path) Append
func (p *Path) Append(q *Path) *PathAppend adds all segments of q.
func (*Path) Arc
func (p *Path) Arc(cx, cy, r float32, a0, sweep float64) *PathArc appends a circular arc centred at (cx,cy) from angle a0 sweeping by sweep radians (positive = clockwise in y-down space). If the path is empty or closed it starts with MoveTo, otherwise with LineTo.
func (*Path) Bounds
func (p *Path) Bounds() geom.RectBounds returns the control-point bounding box.
func (*Path) Circle
func (p *Path) Circle(cx, cy, r float32) *PathCircle appends a closed clockwise circle.
func (*Path) Close
func (p *Path) Close() *PathClose closes the current subpath.
func (*Path) CubeTo
func (p *Path) CubeTo(c1x, c1y, c2x, c2y, x, y float32) *PathCubeTo adds a cubic Bézier.
func (*Path) Current
func (p *Path) Current() geom.PointCurrent returns the pen position.
func (*Path) Flatten
func (p *Path) Flatten(tol float32) []PolylineFlatten converts curves to line segments with the given tolerance.
func (*Path) LineTo
func (p *Path) LineTo(x, y float32) *PathLineTo adds a straight segment.
func (*Path) MoveTo
func (p *Path) MoveTo(x, y float32) *PathMoveTo starts a new subpath.
func (*Path) QuadTo
func (p *Path) QuadTo(cx, cy, x, y float32) *PathQuadTo adds a quadratic Bézier.
func (*Path) RRect
func (p *Path) RRect(r geom.Rect, rad geom.Radii) *PathRRect appends a closed rounded rectangle, clockwise.
func (*Path) Rect
func (p *Path) Rect(r geom.Rect) *PathRect appends a closed rectangle.
func (*Path) Reversed
func (p *Path) Reversed() *PathReversed returns the path with every subpath's direction reversed (used to punch holes under the non-zero rule).
func (*Path) Rotated
func (p *Path) Rotated(angle float64, cx, cy float32) *PathRotated returns a copy rotated by angle radians around (cx, cy).
func (*Path) Skewed
func (p *Path) Skewed(k float32) *PathSkewed returns a copy of p slanted horizontally around y = 0 (the glyph baseline): x' = x - k*y, so points above the baseline (y < 0) move right.
func (*Path) Transform
func (p *Path) Transform(m geom.Affine) *PathTransform returns a copy with every point mapped through m. Affine maps keep Bézier segments exact, so no flattening is needed.
func (*Path) Transformed
func (p *Path) Transformed(s, dx, dy float32) *PathTransformed returns a copy scaled by s then translated by (dx,dy).
Polyline
type Polyline struct {
Pts []geom.Point
Closed bool
}Polyline is a flattened subpath.
Pop
type Pop struct{}Pop ends the innermost PushClip / PushOpacity / PushTransform.
PushClip
type PushClip struct {
Rect geom.Rect
Radii geom.Radii
}PushClip restricts subsequent drawing to a (rounded) rectangle until the matching Pop.
PushOpacity
type PushOpacity struct{ Alpha float32 }PushOpacity draws subsequent commands into a group composited with alpha.
PushTransform
type PushTransform struct{ M geom.Affine }PushTransform maps every subsequent command through M (composed with any enclosing transform: points go through M first, then the outer transforms) until the matching Pop. Clips and opacity groups nest freely inside and around it.
Renderer 实验性
type Renderer interface {
Render(l *List, size geom.Size, scale float32) error
}Renderer turns a List into pixels. The CPU renderer targets an *image.RGBA; GPU renderers target a swapchain owned by the platform host. size is the logical frame size and scale the device pixel ratio.
Implementations must handle every drawing Op type in this package; the hint ops Damage and ScrollRegion may be ignored (redraw everything). Push* ops (PushClip, PushOpacity, PushTransform) form a stack closed by Pop in LIFO order; a renderer keeps the current transform on that stack (identity at the start of a frame) and applies it to all geometry, including clips, shadows, glyphs and images. Renderers that cannot rasterize a rotated glyph or image natively may fall back to filling the transformed outline (Path.Transform) or sampling the image through the inverse transform, as the CPU renderer does.
ScrollRegion 实验性
type ScrollRegion struct {
Rect geom.Rect
Delta geom.Point
}ScrollRegion is a redraw hint: the pixels inside Rect moved by Delta since the previous frame (a pixel at p is now at p+Delta, clipped to Rect), so a renderer may copy them instead of redrawing. The strip the copy leaves uncovered and anything inside Rect that did not move with the content are covered by Damage hints of the same frame. Coordinates follow the same rule as Damage. Renderers apply every ScrollRegion of a frame before redrawing its Damage.
Seg
type Seg struct {
Op SegOp
P [3]geom.Point
}Seg is one path segment; only the first N points are meaningful (Move/Line 1, Quad 2, Cubic 3, Close 0).
SegOp
type SegOp uint8SegOp is a path segment verb.
Append-only: never reorder or insert; the zero value stays SegMove.
const (
SegMove SegOp = iota
SegLine
SegQuad
SegCubic
SegClose
)Shadow
type Shadow struct {
X, Y, Blur, Spread float32
Color color.NRGBA
}Shadow is one CSS box-shadow layer (outer only).
ShadowGeom 实验性
type ShadowGeom struct {
// Shape is the shadow's rounded rectangle in logical pixels: the op's
// Rect offset by (X, Y) and expanded by Spread, with ShapeRadii the
// radii grown by Spread (not below 0). A shadow without blur is this
// shape filled as FillRect fills it.
Shape geom.Rect
ShapeRadii geom.Radii
// Rect is Shape in device pixels, each edge rounded to the nearest
// pixel (as clip rectangles are), and Radii its corner radii: clamped
// to half the shorter side of Shape, scaled and truncated to whole
// device pixels. Sigma is Blur*scale/2 truncated to 1/16 px. These are
// the shadow mask cache's key, so a mask depends only on its key.
Rect image.Rectangle
Radii geom.Radii
Sigma float32
// Margin is how many device pixels the blurred shadow reaches beyond
// Rect: ceil(3s), s = sqrt(Sigma² + 1/12) as in ShadowCoverage.
Margin int
}ShadowGeom is the device geometry paint.CPU draws a ShadowRect with (ShadowPlacement); the GPU renderer draws the same.
func ShadowPlacement 实验性
func ShadowPlacement(o ShadowRect, scale float32) (g ShadowGeom, blurred bool)ShadowPlacement returns the device geometry of o at scale. blurred is false when o has no blur (Blur <= 0 or NaN): then only Shape and ShapeRadii are set. A blurred shadow with an empty Rect draws nothing; otherwise its pixel (x, y) has coverage ShadowCoverage(x+0.5, y+0.5, Rect, Radii, Sigma) within Margin pixels of Rect and 0 beyond.
ShadowRect 实验性
type ShadowRect struct {
Rect geom.Rect
Radii geom.Radii
Shadow Shadow
}ShadowRect draws a blurred box shadow behind a rounded rectangle.
Stop
type Stop struct {
Offset float32
Color color.NRGBA
}Stop is one gradient color stop; Offset runs 0..1 along the gradient.
StrokeRect
type StrokeRect struct {
Rect geom.Rect
Radii geom.Radii
Width float32
Color color.NRGBA
Dash []float32
}StrokeRect draws a border inside the rounded rectangle (CSS border-box).
StrokeStyle
type StrokeStyle struct {
Width float32
Cap Cap
// Round joins are always used; they look right for UI icons.
Dash []float32 // on/off lengths; nil = solid
}StrokeStyle configures StrokePath.
Text 实验性
type Text struct {
Origin geom.Point
Glyphs []Glyph
Color color.NRGBA
}Text draws glyphs.