Namespace
Drupal\color_field
File
-
src/ColorRGB.php
View source
<?php
declare (strict_types=1);
namespace Drupal\color_field;
class ColorRGB extends ColorBase {
protected int $red;
protected int $green;
protected int $blue;
public function __construct(int $red, int $green, int $blue, float $opacity) {
$this->red = max(0, min(255, $red));
$this->green = max(0, min(255, $green));
$this->blue = max(0, min(255, $blue));
$this->opacity = $opacity;
}
public function getRed() : int {
return $this->red;
}
public function getGreen() : int {
return $this->green;
}
public function getBlue() : int {
return $this->blue;
}
public function toString(bool $opacity = TRUE) : string {
$output = $opacity ? 'rgba(' . $this->getRed() . ',' . $this->getGreen() . ',' . $this->getBlue() . ',' . $this->getOpacity() . ')' : 'rgb(' . $this->getRed() . ',' . $this->getGreen() . ',' . $this->getBlue() . ')';
return strtolower($output);
}
public function toHex() : ColorHex {
return new ColorHex($this->intToColorHex($this->getRed()) . $this->intToColorHex($this->getGreen()) . $this->intToColorHex($this->getBlue()), $this->intToColorHex($this->getOpacity() * 255));
}
public function toRgb() : ColorRGB {
return $this;
}
public function toHsl() : ColorHSL {
$r = $this->getRed() / 255;
$g = $this->getGreen() / 255;
$b = $this->getBlue() / 255;
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$l = ($max + $min) / 2;
if ($max === $min) {
$h = $s = 0;
}
else {
$d = $max - $min;
$s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);
switch ($max) {
case $r:
$h = ($g - $b) / $d + ($g < $b ? 6 : 0);
break;
case $g:
$h = ($b - $r) / $d + 2;
break;
case $b:
$h = ($r - $g) / $d + 4;
break;
}
$h /= 6;
}
$h = floor($h * 360);
$s = floor($s * 100);
$l = floor($l * 100);
return new ColorHSL(intval($h), intval($s), intval($l), $this->getOpacity());
}
protected function intToColorHex(int $color) : string {
return str_pad(dechex($color), 2, '0', STR_PAD_LEFT);
}
}
Classes
| Title |
Deprecated |
Summary |
| ColorRGB |
|
RGB represents the RGB color format. |