CGGradient is a Core Graphics object that represents a smooth transition between two or more colors. Unlike drawing a gradient through a loop with color changes, CGGradient uses hardware-accelerated computation and supports two types: linear (axial) and radial. According to Apple Documentation (2026), CGGradient is used to create realistic fills, background effects, and simulate light sources in iOS and macOS interfaces.
Key Takeaways
CGGradient is an immutable object in Core Graphics that encapsulates a set of colors and rules for blending them along a gradient transition. Internally, CGGradient stores an array of CGColor values, an array of locations in the range [0.0, 1.0], and a reference to the CGColorSpace in which the colors are interpreted. Each color is associated with a position on the gradient scale: position 0.0 corresponds to the start, 1.0 to the end of the transition.
When creating a CGGradient using the CGGradientCreateWithColors function, Core Graphics precomputes intermediate color values. A gradient can contain an arbitrary number of color stops, allowing complex multi-color transitions. The number of colors must be at least two, and each color must correspond to a position in the locations array.
The architecture of CGGradient differs from higher-level APIs such as CAGradientLayer from Core Animation in that it works directly in the Core Graphics context. This provides full control over the drawing process and the ability to combine gradients with other Quartz 2D operations — clipping masks, shadows, and transformations.
Core Graphics supports two types of gradients: linear (axial) and radial. A linear gradient is created using the CGGradientCreateWithColors function and drawn with CGContextDrawLinearGradient. A radial gradient requires the same CGGradient structure but is drawn using CGContextDrawRadialGradient.
| Type | Drawing Function | Parameters | Usage |
|---|---|---|---|
| Linear | CGContextDrawLinearGradient | startPoint, endPoint, options | Backgrounds, buttons, progress bars |
| Radial | CGContextDrawRadialGradient | startCenter, startRadius, endCenter, endRadius, options | Highlights, light sources, shadows |
Linear gradient stretches the color transition along a straight line from the start point startPoint to the end point endPoint. Colors are interpolated between these two points, and behavior beyond them is controlled by extend options. A linear gradient is ideal for creating smooth backgrounds, simulating metallic surfaces, and color transitions in interface elements.
Radial gradient creates a color transition from one circle to another. Each circle is defined by a center (startCenter / endCenter) and a radius (startRadius / endRadius). Color interpolates from the inner circle to the outer circle. A special case is when the start radius is 0: the gradient radiates from a single point. Radial gradients are used to simulate light sources, lenses, celestial bodies, and spotlight effects.
CGGradient is created with only one base function — CGGradientCreateWithColors. The function takes a CGColorSpace, an array of CGColor (CFArray), and an array of CGFloat locations. If locations is NULL, colors are distributed evenly along the gradient scale. If locations are specified, their count must match the number of colors.
The locations array contains values from 0.0 to 1.0 that define the stop points for each color. Values must increase monotonically. If the first value is greater than 0.0, the color from the start to this position is extrapolated from the color at position 0.0. Similarly for the last value less than 1.0. This behavior is controlled by the extend options during drawing.
When choosing colors for a gradient, it is important to consider the color space. All colors in a single CGGradient must belong to the same CGColorSpace — Core Graphics interpolates components in that space. If colors are created in different spaces, they must first be converted to a common space using CGColorCreateCopyByMatchingToColorSpace.
Core Graphics provides two functions for drawing a gradient: CGContextDrawLinearGradient for linear and CGContextDrawRadialGradient for radial. Both functions accept a graphics context, a CGGradient object, extend options, and type-specific geometric parameters. Drawing is performed taking into account the current clipping mask and context transformation.
Extend options control the behavior of the gradient beyond the 0.0–1.0 position range. The constant kCGGradientDrawsBeforeStartLocation fills the area before the start position with the color of the first stop. kCGGradientDrawsAfterEndLocation fills with the color of the last stop. These options can be combined using a bitmask. For radial gradients, the options apply to the area beyond the start and end radii.
The gradient is drawn in the coordinate system of the current graphics context, taking into account its transformation (CTM — Current Transformation Matrix). Applying CGContextTranslateCTM, CGContextScaleCTM, or CGContextRotateCTM before calling the drawing function changes the position and scale of the gradient. This allows reusing a single CGGradient for different areas without creating new objects.
Core Graphics provides several additional mechanisms for controlling gradients: antialiasing, masking through a clipping mask, and combining with transparency effects. Antialiasing is enabled by default in the graphics context and is controlled via CGContextSetShouldAntialias.
Clipping mask allows you to restrict the gradient drawing area to an arbitrary shape. Before calling CGContextDrawLinearGradient, you need to define a path using CGContextBeginPath, CGContextAddPath, and CGContextClip. The gradient is drawn only within the area bounded by this path. This is widely used for creating gradient icons, buttons, and progress bars.
Gradient extending is another important parameter. When using kCGGradientDrawsBeforeStartLocation, Core Graphics extrapolates the color of the first stop over the entire area before startPoint. Without this option, the area outside the gradient remains unfilled (transparent). Combining both options ensures that the entire graphics context rectangle is filled with a gradient, even if startPoint and endPoint are inside it.
Let us look at practical examples of creating and drawing gradients in iOS using CGGradient and Core Graphics.
This example creates a linear gradient with three colors (blue, green, red) and draws it diagonally across a UIView. The locations array distributes colors unevenly: blue from 0.0 to 0.3, green at 0.6, red from 0.6 to 1.0.
func drawLinearGradient(in ctx: CGContext,
rect: CGRect) {
let colors = [
UIColor.blue.cgColor,
UIColor.green.cgColor,
UIColor.red.cgColor
] as CFArray
let locations: [CGFloat] = [0.0, 0.6, 1.0]
let space = CGColorSpaceCreateDeviceRGB()
guard let gradient = CGGradientCreateWithColors(
space, colors, locations
) else { return }
let start = CGPoint(x: 0, y: 0)
let end = CGPoint(x: rect.width,
y: rect.height)
ctx.drawLinearGradient(gradient,
start: start, end: end,
options: [.drawsBeforeStartLocation,
.drawsAfterEndLocation])
}
This example draws a radial gradient simulating a glow effect. The start point with zero radius defines the glow center, and the outer circle defines the fade boundary. This effect is used for highlighting interface elements or activity indicators.
func drawRadialGlow(in ctx: CGContext,
center: CGPoint) {
let colors = [
UIColor.white.cgColor,
UIColor.orange.cgColor,
UIColor.clear.cgColor
] as CFArray
let locations: [CGFloat] = [0.0, 0.4, 1.0]
let gradient = CGGradientCreateWithColors(
CGColorSpaceCreateDeviceRGB(), colors, locations)
ctx.drawRadialGradient(gradient,
startCenter: center, startRadius: 0,
endCenter: center, endRadius: 100,
options: [.drawsBeforeStartLocation,
.drawsAfterEndLocation])
}
In this example, the gradient is restricted to a circular area using a clipping path. Before drawing the gradient, a circular path is defined, which becomes the current context mask. The gradient fills only the area inside the circle, creating a gradient icon effect.
func drawGradientInCircle(in ctx: CGContext,
rect: CGRect) {
// Creating circular clip path
let circlePath = CGMutablePath()
circlePath.addEllipse(in: rect)
ctx.addPath(circlePath)
ctx.clip()
// Drawing gradient inside clip mask
let colors = [UIColor.magenta.cgColor,
UIColor.cyan.cgColor]
let gradient = CGGradientCreateWithColors(
CGColorSpaceCreateDeviceRGB(),
colors as CFArray, nil)
ctx.drawLinearGradient(gradient,
start: CGPoint(x: 0, y: 0),
end: CGPoint(x: rect.width,
y: rect.height),
options: [.drawsBeforeStartLocation])
}
Frequently Asked Questions
CGGradient is a low-level Core Graphics object for drawing in a graphics context. CAGradientLayer is a high-level Core Animation layer with automatic animation and hardware acceleration. CAGradientLayer is easier to use with UIKit, but CGGradient provides full control and compatibility with any CGContext.
Minimum is 2 colors. The upper limit is only constrained by available memory, since Core Graphics stores an array of colors and a precomputed interpolation table. In practice, more than 10–15 colors in a single gradient is unnecessary — the visual transition becomes indistinguishable from a smooth one.
Use a CGColor with an alpha channel less than 1.0 in the color array. For example, a color with transparency is created as UIColor(red: 0, green: 0, blue: 1, alpha: 0.5).cgColor. Core Graphics interpolates the alpha channel just like color components, creating a smooth transparency transition.
Yes, CGGradient is part of Core Graphics, available on both platforms: iOS and macOS. On macOS, the gradient is drawn in any NSView by overriding drawRect. All functions CGGradientCreateWithColors, CGContextDrawLinearGradient, and CGContextDrawRadialGradient are identical on both platforms.
To rotate a gradient, apply a transformation to the graphics context before drawing: CGContextRotateCTM(ctx, angle). The start and end points of the gradient are specified in the local coordinate system of the context after transformation. Alternatively, you can compute the rotated coordinates of the points directly without changing the CTM.
Summary
CGContextDrawLinearGradientCGContextDrawRadialGradientWe will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also