1
0

RGB.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace fphammerle\helpers\colors;
  3. class RGB
  4. {
  5. use \fphammerle\helpers\PropertyAccessTrait;
  6. const comparison_precision = 0.00001;
  7. private $_red;
  8. private $_green;
  9. private $_blue;
  10. public function __construct($red = 0, $green = 0, $blue = 0)
  11. {
  12. $this->setRed($red);
  13. $this->setGreen($green);
  14. $this->setBlue($blue);
  15. }
  16. public function getRed()
  17. {
  18. return $this->_red;
  19. }
  20. public function setRed($red)
  21. {
  22. $red = (float)$red;
  23. if($red < 0 || $red > 1) {
  24. throw new \UnexpectedValueException('value must be within [0, 1]');
  25. }
  26. $this->_red = $red;
  27. }
  28. public function getGreen()
  29. {
  30. return $this->_green;
  31. }
  32. public function setGreen($green)
  33. {
  34. $green = (float)$green;
  35. if($green < 0 || $green > 1) {
  36. throw new \UnexpectedValueException('value must be within [0, 1]');
  37. }
  38. $this->_green = $green;
  39. }
  40. public function getBlue()
  41. {
  42. return $this->_blue;
  43. }
  44. public function setBlue($blue)
  45. {
  46. $blue = (float)$blue;
  47. if($blue < 0 || $blue > 1) {
  48. throw new \UnexpectedValueException('value must be within [0, 1]');
  49. }
  50. $this->_blue = $blue;
  51. }
  52. public function equals(RGB $other)
  53. {
  54. return abs($this->red - $other->red) < self::comparison_precision
  55. && abs($this->green - $other->green) < self::comparison_precision
  56. && abs($this->blue - $other->blue) < self::comparison_precision;
  57. }
  58. public function getTuple()
  59. {
  60. return [$this->red, $this->green, $this->blue];
  61. }
  62. public function getDigitalTuple($bits)
  63. {
  64. $bits = (int)$bits;
  65. $factor = (2 << ($bits - 1)) - 1;
  66. $tuple = $this->tuple;
  67. return array_map(function($v) use ($factor) { return (int)round($v * $factor); }, $tuple);
  68. }
  69. }