How It Works
GradientMesh treats a 2D gradient as a geometry and interpolation problem.
Instead of drawing a static bitmap gradient, it builds mesh vertices, assigns colors to those vertices, and lets the renderer interpolate color values across triangles.
Rectangular gradient mesh
For a rectangular gradient, the mesh is built as a regular grid:
v1 ----- v2 ----- v3
| \ | \ |
| \ | \ |
v4 ----- v5 ----- v6
| \ | \ |
| \ | \ |
v7 ----- v8 ----- v9Each grid cell is split into two triangles:
(v1, v2, v5)
(v1, v5, v4)If a rectangle has width
For each cell, the two triangles can be represented as:
Color interpolation
Inside a triangle, the renderer interpolates vertex colors.
Conceptually, a simple two-color gradient can be written as:
where:
For a triangle, this idea generalizes through barycentric interpolation.
If a point inside a triangle has barycentric weights
and the interpolated color is:
That is the small trick behind the visual result: the Lua code builds the geometry, while the rendering pipeline does the smooth color blending.
Radial and polygon gradients
For circular and polygon-based gradients, the library creates rings of vertices around a center point.
A radial vertex can be described as:
where:
is the center point; and are scale factors from scalePolygon;is the base radius; and are normalized radial percentages for the current color stop; is the angular position of the current polygon vertex.
For a regular polygon with
where rotationMesh, expressed in radians.
This is why the same function can produce circles, ellipses, regular polygons, rotated polygons, and radial texture masks: changing
Inner holes
When hole = true, the radial mesh starts from an inner radius instead of the center.
If
For multiple radial color stops, the intermediate percentages can be distributed between the inner and outer radius:
where
This creates donut-like gradients and ring-shaped meshes while keeping the same polygon construction logic.
Antialiasing ring
When jaggedFree = true, the mesh adds a thin outer fade ring.
Conceptually, it creates one ring close to the edge:
and another one at the final boundary:
Then the outer alpha fades toward zero:
This soft transparent ring helps reduce jagged polygon edges.
Texture coordinates
When a texture is attached, the mesh also generates texture coordinates.
For a rectangular mesh, texture coordinates follow the same normalized grid idea:
where:
and are the texture width and height; and are the visible texture dimensions after scaling; and are the texture anchor values.
For polygon meshes, the texture coordinates follow the same radial idea as the geometric vertices, which is what allows image textures to be clipped, rotated, and tinted by polygon geometry.