MeshGradient

A two-dimensional gradient defined by a 2D grid of positioned colors.

StructureiOS 18.0+macOS 15.0+tvOS 18.0+watchOS 11.0+visionOS 2.0+MeshGradient in SwiftUI

Declaration

React
type MeshGradient =
  | { width: number; height: number; bezierPoints: MeshGradientBezierPoint[]; colors: Color[]; background?: Color; smoothsColors?: boolean; colorSpace?: GradientColorSpace; }
  | { width: number; height: number; bezierPoints: MeshGradientBezierPoint[]; resolvedColors: ColorResolved[]; background?: Color; smoothsColors?: boolean; colorSpace?: GradientColorSpace; }
  | { width: number; height: number; locations: MeshGradientLocations; colors: MeshGradientColors; background?: Color; smoothsColors?: boolean; colorSpace?: GradientColorSpace; }
  | { width: number; height: number; points: [ x: number, y: number ][]; colors: Color[]; background?: Color; smoothsColors?: boolean; colorSpace?: GradientColorSpace; }
  | { width: number; height: number; points: [ x: number, y: number ][]; resolvedColors: ColorResolved[]; background?: Color; smoothsColors?: boolean; colorSpace?: GradientColorSpace; };
Swift
nonisolated struct MeshGradient

Overview

Each vertex has a position, a color and four surrounding Bezier control points (leading, top, trailing, bottom) that define the tangents connecting the vertex with its four neighboring vertices. (Vertices on the corners or edges of the mesh have less than four neighbors, they ignore their extra control points.) Control points may either be specified explicitly or implicitly.

When rendering, a tessellated sequence of Bezier patches are created, and vertex colors are interpolated across each patch, either linearly, or via another set of cubic curves derived from how the colors change between neighbors -- the latter typically gives smoother color transitions.

MeshGradient(width: 3, height: 3, points: [
    .init(0, 0), .init(0.5, 0), .init(1, 0),
    .init(0, 0.5), .init(0.5, 0.5), .init(1, 0.5),
    .init(0, 1), .init(0.5, 1), .init(1, 1)
], colors: [
    .red, .purple, .indigo,
    .orange, .white, .blue,
    .yellow, .green, .mint
])

From Apple’s SwiftUI documentation. Code samples there are Swift.

See also

More in Drawing and shapes.