-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpriteMapper.php
More file actions
107 lines (85 loc) · 2.58 KB
/
SpriteMapper.php
File metadata and controls
107 lines (85 loc) · 2.58 KB
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
<?php
namespace SCG\SpriteMapper;
use SCG\SpriteMapper\Sprite;
use SCG\SpriteMapper\Spritepacker;
class SpriteMapper
{
private $config;
private $root = [];
private $height = 0;
private $width = 0;
private $sprites = [];
private $sprites_data = [];
private static $defaults = [
'type' => 'png',
'fill' => 'transparent',
'compression' => 70
];
public function __construct ( $config = [] )
{
$this->config = array_merge(self::$defaults, $config);
}
public function __get ( $name )
{
return $this->{$name};
}
public function add ($sprite_url)
{
$sprite = new Sprite($sprite_url);
$this->sprites[] = $sprite;
return $sprite;
}
public function removeSprite ( Sprite $sprite )
{
if ($key = array_search($sprite, $this->sprites, true)) {
array_splice($this->sprites, $key, 1);
return true;
}
return false;
}
public function save ()
{
$contents = $this->render(false);
}
public function render ( $echo = true )
{
ob_start();
//
$this->generateSpritemap();
$contents = ob_get_clean();
if ($echo === true) {
echo $contents;
} else {
return $contents;
}
}
private function generateSpritemap ()
{
// Fisrt, sort the nodes from biggest to smallest
$sprites = $this->sprites;
$len = count($sprites);
$node;
usort($sprites, function ( $a, $b ) {
$asa = $a->height;
$bsa = $b->height;
return ($asa > $bsa) ? -1 : 1;
});
$packer = new SpritePacker;
$packer->fit($sprites);
$this->width = $packer->pack->w;
$this->height = $packer->pack->h;
$spritemap = imagecreatetruecolor($this->width, $this->height);
$color = imagecolorallocatealpha($spritemap, 255, 255, 255, 127);
imagefill($spritemap, 0, 0, $color);
imagecolortransparent($spritemap, imagecolorallocatealpha($spritemap, 0, 0, 0, 127));
imagealphablending($spritemap, false);
imagesavealpha($spritemap, true);
foreach ($sprites as $sprite) {
if ($sprite->fit) {
$fit = $sprite->fit;
imagecopyresampled($spritemap, $sprite->getResource(), $fit->x, $fit->y, 0, 0, $sprite->width, $sprite->height, $sprite->original_width, $sprite->original_height);
}
}
imagepng($spritemap, __DIR__.'/test.png');
}
}