Skip to main content

HexColor

Renfordt\Colors\HexColor

Represents a color as a hexadecimal string. Accepts 3-, 4-, 6-, and 8-digit forms, with or without a leading #. The 4- and 8-digit forms carry an alpha (opacity) channel (#RGBA / #RRGGBBAA). Implements \Stringable.

Properties

PropertyTypeNotes
hexstringRead returns the value with a # prefix. Assignment validates the format and throws InvalidArgumentException if it is not 3, 4, 6, or 8 hex digits.

Validation

The leading # is optional on assignment and is stripped before validation. The remaining string must be exactly 3, 4, 6, or 8 characters, each a hexadecimal digit (0–9, a–f, A–F). Anything else raises InvalidArgumentException.

HexColor::create('#FF5733'); // ok (6-digit)
HexColor::create('F53'); // ok (3-digit)
HexColor::create('#FF5733CC'); // ok (8-digit, with alpha)
HexColor::create('F53C'); // ok (4-digit, with alpha)
HexColor::create('xyz'); // throws InvalidArgumentException

Alpha handling

A fully opaque alpha is normalized away so that opaque colors always render in their plain 3-/6-digit form: #FF0000FF is stored as #FF0000 and #F00F as #F00. Use getAlpha() to read the alpha as an int 0255 (it returns 255 when the string carries no alpha digits).

HexColor::create('#FF0000FF')->getHexStr(); // #ff0000
HexColor::create('#FF000080')->getAlpha(); // 128
HexColor::create('#FF0000')->getAlpha(); // 255

Static methods

create(string $hexStr): HexColor

Creates an instance from a hex string.

make(string $hexStr): HexColor

Alias of create().

Instance methods

getHexStr(bool $withHash = true): string

Returns the hex string. When $withHash is true (default) the result is prefixed with #; otherwise it is returned without the prefix.

$hex = HexColor::create('FF5733');
echo $hex->getHexStr(); // #FF5733
echo $hex->getHexStr(false); // FF5733

getAlpha(): int

Returns the alpha (opacity) component as an int 0255. Returns 255 (fully opaque) when the hex string has no alpha digits. A 4-digit alpha nibble is expanded (e.g. 80x88).

getName(): ?string

Returns the standard color name that matches this color exactly, or null when no standard color matches. See NamedColor.

HexColor::create('#ff6347')->getName(); // "tomato"

toRGB(): RGBColor

Converts to RGBColor. A 6- or 8-digit string is parsed with bitwise operations; a 3- or 4-digit string has each digit doubled before parsing. The alpha digits, when present, become the RGB color's alpha component.

toHSL(int $precision = 4): HSLColor

Converts to HSLColor via RGB. $precision controls rounding.

toHSV(int $precision = 4): HSVColor

Converts to HSVColor via RGB. $precision controls rounding.

__toString(): string

Returns the hex string with the # prefix.

echo (string) HexColor::create('FF5733'); // #FF5733