Skip to main content

Manipulating colors

Adjusting lightness

HSLColor provides brighten() and darken() to change the lightness component. Both take an integer percentage and default to 10.

$color = HSLColor::create([200, 0.6, 0.5]);

$color->brighten(20); // lightness += 0.20
$color->darken(15); // lightness -= 0.15

These methods modify the instance in place and return void. The amount is divided by 100 and added to or subtracted from the current lightness. The result is clamped to the 0.0–1.0 range:

$color = HSLColor::create([200, 0.6, 0.9]);
$color->brighten(50);
echo $color->lightness; // 1.0 (clamped)

HSVColor does not provide these helpers. Adjust its value property directly, which is clamped on assignment:

$hsv = HSVColor::create([200, 0.6, 0.5]);
$hsv->value = 0.8;

Editing components directly

Every component is a public property and can be assigned directly. Numeric components are clamped to their valid range:

$rgb = RGBColor::create([255, 100, 50]);
$rgb->red = 200;
$rgb->green = 300; // clamped to 255
$rgb->blue = -10; // clamped to 0

For hex colors, assigning the hex property runs format validation and throws InvalidArgumentException on invalid input:

$hex = HexColor::create('#FFFFFF');
$hex->hex = '#000000'; // ok
$hex->hex = 'xyz'; // throws InvalidArgumentException

Adjusting opacity

RGBColor, HSLColor, and HSVColor expose alpha as a clamped property. RGB uses an int 0255; HSL and HSV use a float 0.01.0:

$rgb = RGBColor::create([255, 100, 50]);
$rgb->alpha = 128; // 50% opaque
$rgb->alpha = 400; // clamped to 255

$hsl = HSLColor::create([200, 0.6, 0.5]);
$hsl->alpha = 0.5; // 50% opaque
$hsl->alpha = -1; // clamped to 0.0

HexColor has no writable alpha property. Build a new hex value with the alpha digits instead, or round-trip through RGBColor:

$hex = HexColor::create('#FF6432')->toRGB();
$hex->alpha = 128;
$translucent = $hex->toHex(); // #ff643280