-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathPictureBox.php
118 lines (93 loc) · 2.95 KB
/
PictureBox.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
namespace SimonHamp\TheOg\Layout;
use Imagick;
use ImagickDraw;
use ImagickPixel;
use Intervention\Image\ImageManager;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
use SimonHamp\TheOg\Theme\PicturePlacement;
class PictureBox extends Box
{
/**
* @var array<callable<Imagick>>
*/
public array $maskQueue;
public string $path;
public PicturePlacement $placement = PicturePlacement::Natural;
protected ImageInterface $picture;
public function render(): void
{
if (! empty($this->maskQueue)) {
foreach ($this->maskQueue as $mask) {
$this->mask($mask());
}
}
$position = $this->calculatePosition();
$this->canvas()->place(
element: $this->getPicture(),
offset_x: $position->x(),
offset_y: $position->y()
);
}
/**
* Apply a mask image to the picture.
*
* @param Imagick $mask
*/
public function mask(Imagick $mask): void
{
$base = $this->getPicture()->core()->native();
$base->setImageMatte(true);
$base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0);
}
public function circle(): static
{
$this->maskQueue[] = function () {
$width = $this->dimensions()->width();
$start = intval(floor($width / 2));
// Create the circle
$circle = new ImagickDraw();
$circle->setFillColor(new ImagickPixel('#fff'));
$circle->circle($start, $start, $start, $width - 10);
// Draw it to an Imagick instance
$image = new Imagick();
$image->newImage($width, $width, 'none', 'png');
$image->setImageMatte(true);
$image->drawImage($circle);
return $image;
};
return $this;
}
public function path(string $path): static
{
$this->path = $path;
return $this;
}
public function placement(PicturePlacement $placement): static
{
$this->placement = $placement;
return $this;
}
protected function getPicture(): ImageInterface
{
$this->picture ??= ImageManager::imagick()
->read(file_get_contents($this->path));
match ($this->placement) {
PicturePlacement::Cover => $this->picture->cover($this->box->width(), $this->box->height()),
PicturePlacement::Natural => $this->picture->scaleDown($this->box->width(), $this->box->height()),
};
return $this->picture;
}
/**
* Get the box that will be rendered without calculating its position on the canvas.
*
* @return SizeInterface
*/
public function dimensions(): SizeInterface
{
// Using the picture and its placement we can calculate
// the relative dimensions based on the initial box.
return $this->getPicture()->size();
}
}