TransformationMatrix.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types = 1);
  3. namespace BaconQrCode\Renderer\Image;
  4. final class TransformationMatrix
  5. {
  6. /**
  7. * @var float[]
  8. */
  9. private $values;
  10. public function __construct()
  11. {
  12. $this->values = [1, 0, 0, 1, 0, 0];
  13. }
  14. public function multiply(self $other) : self
  15. {
  16. $matrix = new self();
  17. $matrix->values[0] = $this->values[0] * $other->values[0] + $this->values[2] * $other->values[1];
  18. $matrix->values[1] = $this->values[1] * $other->values[0] + $this->values[3] * $other->values[1];
  19. $matrix->values[2] = $this->values[0] * $other->values[2] + $this->values[2] * $other->values[3];
  20. $matrix->values[3] = $this->values[1] * $other->values[2] + $this->values[3] * $other->values[3];
  21. $matrix->values[4] = $this->values[0] * $other->values[4] + $this->values[2] * $other->values[5]
  22. + $this->values[4];
  23. $matrix->values[5] = $this->values[1] * $other->values[4] + $this->values[3] * $other->values[5]
  24. + $this->values[5];
  25. return $matrix;
  26. }
  27. public static function scale(float $size) : self
  28. {
  29. $matrix = new self();
  30. $matrix->values = [$size, 0, 0, $size, 0, 0];
  31. return $matrix;
  32. }
  33. public static function translate(float $x, float $y) : self
  34. {
  35. $matrix = new self();
  36. $matrix->values = [1, 0, 0, 1, $x, $y];
  37. return $matrix;
  38. }
  39. public static function rotate(int $degrees) : self
  40. {
  41. $matrix = new self();
  42. $rad = deg2rad($degrees);
  43. $matrix->values = [cos($rad), sin($rad), -sin($rad), cos($rad), 0, 0];
  44. return $matrix;
  45. }
  46. /**
  47. * Applies this matrix onto a point and returns the resulting viewport point.
  48. *
  49. * @return float[]
  50. */
  51. public function apply(float $x, float $y) : array
  52. {
  53. return [
  54. $x * $this->values[0] + $y * $this->values[2] + $this->values[4],
  55. $x * $this->values[1] + $y * $this->values[3] + $this->values[5],
  56. ];
  57. }
  58. }