Skip to content

Novis\Image\Color::rgba

Makes a colour from its red, green, blue and alpha values.

Color::rgba($r, $g, $b, $alpha) returns a Color. Red, green and blue are whole numbers from 0 to 255. Alpha is how opaque the colour is: 0.0 is fully transparent and 1.0 is fully opaque. If you leave alpha out, it is 1.0.

The four values are on the Color as r, g, b and alpha, and you cannot change them. A channel above 255 throws a LogicError. An alpha below 0.0, above 1.0 or NAN also throws a LogicError.

You give a Color to the image methods that need one: Image::create fills a new image with it, flattened puts it behind transparent pixels, and tinted colours an image with it.

Good to know: Color::hex makes the same colour from text such as "#ff8800". Use it when the colour comes from a setting or a style sheet.

Parameters

  • $ruint
  • $guint
  • $buint
  • $alphafloatdefault 1.0

Return value

Returns Color.

Examples

Make a colour

<?nvs
// Shows how to make a colour and read its four values.
use Novis\Image\Color;
// Alpha is left out, so it is 1.0.
Color $orange = Color::rgba(255, 136, 0);
// This prints 255 136 0 1.
echo $orange->r, ' ', $orange->g, ' ', $orange->b, ' ', $orange->alpha, "\n";
Output
255 136 0 1

Fill the background

<?nvs
// Shows how to put a white background behind a transparent image.
use Novis\Image\Color;
use Novis\Image\Image;
// A new image of 4 by 4 pixels. Alpha is 0.0, so every pixel is transparent.
Image $logo = Image::create(4, 4, Color::rgba(0, 0, 0, 0.0));
// `flattened` returns a copy with the white colour behind the transparent pixels.
var $pixels = $logo->flattened(Color::rgba(255, 255, 255))->raw()->pixels;
array<mixed> $first = Core\Bytes::unpack(Core\Bytes::slice($pixels, 0, 4), 'C4');
// This prints 255 255 255 255.
echo $first[0], ' ', $first[1], ' ', $first[2], ' ', $first[3], "\n";
Output
255 255 255 255

Check a colour from a form

<?nvs
// Shows how to check colour values that a user typed into a form.
use Novis\Image\Color;
class Form
{
public static function color(uint $r, uint $g, uint $b): string
{
try {
Color $c = Color::rgba($r, $g, $b);
return "ok: {$c->r} {$c->g} {$c->b}";
} catch (LogicError $e) {
return 'not a colour';
}
}
}
// The second line has a red value of 300, which is above 255.
// This prints "ok: 20 120 220" and then "not a colour".
echo Form::color(20, 120, 220), "\n";
echo Form::color(300, 120, 220), "\n";
Output
ok: 20 120 220
not a colour