86 lines
2.2 KiB
PHP
86 lines
2.2 KiB
PHP
<?php
|
|
// ColourRGB.php
|
|
// Created: 2023-01-02
|
|
// Updated: 2023-01-02
|
|
|
|
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 = 1.0) {
|
|
$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) {
|
|
$alpha = (string)round($this->alpha, 3);
|
|
return sprintf('rgba(%d, %d, %d, %s)', $this->red, $this->green, $this->blue, $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()
|
|
);
|
|
}
|
|
}
|