我有这个图像功能,我有一点问题
function BuildCustomBricks($myBricksAndRatios) {
$img = imagecreate(890,502);
imagealphablending($img, true);
imagesavealpha($img, true);
foreach ($this->shuffle_with_keys($myBricksAndRatios) as $key) {
$bricks_to_choose = rand(1,10);
$cur = imagecreatefrompng("/var/www/brickmixer/bricks/". $key."-".$bricks_to_choose.".png");
imagealphablending($cur, true);
imagesavealpha($cur, true);
imagecopy($img, $cur, 0, 0, 0, 0, 125, 32);
imagedestroy($cur);
}
header('Content-Type: image/png');
imagepng($img);
}
如何将每个图像放置在前一个像素的100个像素中?
next image in the loop:
imagecopy($img, $cur, previous_x_coord+100, 0, 0, 0, 125, 32);
答案 0 :(得分:1)
只需存储一个从零开始的变量,并在每次循环迭代结束时加100:
// Init at zero
$coords = 0;
foreach ($this->shuffle_with_keys($myBricksAndRatios) as $key) {
$bricks_to_choose = rand(1,10);
$cur = imagecreatefrompng("/var/www/brickmixer/bricks/". $key."-".$bricks_to_choose.".png");
imagealphablending($cur, true);
imagesavealpha($cur, true);
// Use the variable here
imagecopy($img, $cur, $coords, 0, 0, 0, 125, 32);
imagedestroy($cur);
// Add 100 at the end of the loop block
$coords += 100;
}
答案 1 :(得分:1)
Michael的答案是一个选项,但由于您使用的是foreach
而不是while
,因此您也可以使用数组的索引:
foreach ($this->shuffle_with_keys($myBricksAndRatios) as $factor => $key)
{
//...Multiply index by 100: 0*100,1*100,2*100 etc...
imagecopy($img, $cur, 100*$factor, 0, 0, 0, 125, 32);
//...
}
这有点肛门,但它不需要2行额外的代码,也没有额外的变量。批评者可能会说这段代码不易维护,在这种情况下我会说:'不要忍者评论,然后'
警告:
正如迈克尔指出的那样,由于显而易见的原因,此代码不适用于关联数组('First_Key'*100 === ?
)