index/src/Colour/ColourRGB.php

81 lines
2.1 KiB
PHP

<?php
namespace Index\Colour;
class ColourRGB extends Colour {
private int $red;
private int $green;
private int $blue;
private float $alpha;
public function __construct(int $red, int $green, int $blue, float $alpha) {
$this->red = max(0, min(255, $red));
$this->green = max(0, min(255, $green));
$this->blue = max(0, min(255, $blue));
$this->alpha = max(0.0, min(1.0, $alpha));
}
public function getRed(): int {
return $this->red;
}
public function getGreen(): int {
return $this->green;
}
public function getBlue(): int {
return $this->blue;
}
public function getAlpha(): float {
return $this->alpha;
}
public function shouldInherit(): bool {
return false;
}
public function __toString(): string {
if($this->alpha < 1.0)
return sprintf('rgba(%d, %d, %d, %.3F)', $this->red, $this->green, $this->blue, $this->alpha);
return sprintf('#%02x%02x%02x', $this->red, $this->green, $this->blue);
}
public static function fromRawRGB(int $raw): ColourRGB {
return new ColourRGB(
(($raw >> 16) & 0xFF),
(($raw >> 8) & 0xFF),
($raw & 0xFF),
1.0
);
}
public static function fromRawARGB(int $raw): ColourRGB {
return new ColourRGB(
(($raw >> 16) & 0xFF),
(($raw >> 8) & 0xFF),
($raw & 0xFF),
(($raw >> 24) & 0xFF) / 255.0,
);
}
public static function fromRawRGBA(int $raw): ColourRGB {
return new ColourRGB(
(($raw >> 24) & 0xFF),
(($raw >> 16) & 0xFF),
(($raw >> 8) & 0xFF),
($raw & 0xFF) / 255.0,
);
}
public static function convert(Colour $colour): ColourRGB {
if($colour instanceof ColourRGB)
return $colour;
return new ColourRGB(
$colour->getRed(),
$colour->getGreen(),
$colour->getBlue(),
$colour->getAlpha()
);
}
}