ContrastSolver

Solver for complex color contrast problems.

Provides utilities for alpha compositing, finding required alpha for contrast,
and adjusting lightness to meet specific contrast targets.

Methods

public static function adjustLightnessToContrast(ColorInterface $fg, ColorInterface $bg, float $targetRatio, int $quantizePrecision): ColorInterface

Adjust the lightness of a foreground color to meet a target contrast ratio.

Preserves the chroma and hue of the color while searching for the minimal
lightness adjustment in Oklch space. The search verifies each candidate
at $quantizePrecision bits per channel (8 by default, matching a
serialized hex color), so the returned color still meets the target
after that rounding. Pass 0 to search at full float precision instead.

Parameters
NameTypeDefault
$fg ColorInterface -
$bg ColorInterface -
$targetRatio float 4.5
$quantizePrecision int 8

bestOn

static
public static function bestOn(ColorInterface $bg, array $candidates): ColorInterface

Choose the best contrasting color from a list of candidates.

Parameters
NameTypeDefault
$bg ColorInterface -
$candidates array -

composite

static
public static function composite(ColorInterface $fg, ColorInterface $bg): SrgbColor

Composite a foreground color over a background color.

Performs alpha blending in sRGB space and returns the resulting color.

Parameters
NameTypeDefault
$fg ColorInterface -
$bg ColorInterface -
public static function compositedRatio(ColorInterface $fg, ColorInterface $bg): float

Calculate the contrast ratio of a foreground color over a background.

Accounts for the alpha channel of the foreground color by compositing it.

Parameters
NameTypeDefault
$fg ColorInterface -
$bg ColorInterface -

requiredAlpha

static
public static function requiredAlpha(ColorInterface $fg, ColorInterface $bg, float $targetRatio, int $quantizePrecision): float

Find the minimum alpha required for a foreground to reach a target contrast ratio.

Uses binary search to find the minimal alpha value in range [0, 1]. The
search verifies each candidate at $quantizePrecision bits per channel
(8 by default, matching a serialized hex alpha byte), so the returned
alpha still meets the target after that rounding. Pass 0 to search at
full float precision instead.

Parameters
NameTypeDefault
$fg ColorInterface -
$bg ColorInterface -
$targetRatio float 4.5
$quantizePrecision int 8