Novis\Image\Color::hex
Novis\Image\Color::hex(string $hex): ColorNovis\Image\Color::hex( string $hex, ): Color
Makes a colour from text written in hex, such as "#ff8800".
Color::hex($text) returns a Color. The text has two hex digits for each channel: red, green, blue and, if you want, alpha. So "#ff8800" is red 255, green 136 and blue 0. With a fourth pair, "#ff880080", the alpha is 128 out of 255, which is about 0.5. Without it, the alpha is 1.0.
The short forms "#f80" and "#f808" have one digit per channel, and each digit is written twice: "#f80" is the same as "#ff8800". The # is optional, and upper and lower case letters both work.
Any other text throws a LogicError. This includes the wrong number of digits, such as "#12345", and characters that are not hex digits, such as "#gg0000".
Good to know: use Color::rgba when you already have the channels as numbers.
Parameters
$hexstring
Return value
Returns Color.
Examples
The four ways to write it
<?nvs// Shows the four ways to write a colour in hex.use Novis\Image\Color;
array<string> $texts = ['#f80', '#f808', '#ff8800', 'ff880088'];
// Each line prints 255 136 0. The alpha is 1 without a fourth value// and 0.53333333333333 with one.foreach ($texts as string $text) { Color $c = Color::hex($text); echo $text, ': ', $c->r, ' ', $c->g, ' ', $c->b, ' ', $c->alpha, "\n";}#f80: 255 136 0 1#f808: 255 136 0 0.53333333333333#ff8800: 255 136 0 1ff880088: 255 136 0 0.53333333333333A brand colour from settings
<?nvs// Shows how to make a placeholder image in a colour that is stored as text.use Novis\Image\Color;use Novis\Image\Format;use Novis\Image\Image;
// The colour as it might be stored in a setting or a style sheet.string $brand = '#2a6f97';
// A new PNG image of 64 by 64 pixels in that colour.tainted bytes $png = Image::create(64, 64, Color::hex($brand))->withFormat(Format::Png)->encode();
// A PNG file always starts with these 8 bytes. This prints 89504e470d0a1a0a.echo Core\Encoding::toHex(Core\Bytes::slice($png, 0, 8)), "\n";89504e470d0a1a0aText that is not a colour
<?nvs// Shows how to use a default colour when the text is not a colour.use Novis\Image\Color;
class Theme{ public static function color(string $text): Color { try { return Color::hex($text); } catch (LogicError $e) { return Color::hex('#000000'); } }}
// "#12345" has five digits, and "#gg0000" has letters that are not hex.// Both give the default black. This prints 0 128 0, then 0 0 0 twice.array<string> $texts = ['#008000', '#12345', '#gg0000'];foreach ($texts as string $text) { Color $c = Theme::color($text); echo $c->r, ' ', $c->g, ' ', $c->b, "\n";}0 128 00 0 00 0 0