1

我有这个图像功能,但我有一点问题

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);
    }

如何将每张图像放在前一张的 foreach 100 像素中?

next image in the loop:    
imagecopy($img, $cur, previous_x_coord+100, 0, 0, 0, 125, 32);
4

2 回答 2

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;
    }
于 2012-09-14T12:42:20.573 回答
1

迈克尔的回答是一个选项,但是由于您使用的是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 === ?

于 2012-09-14T12:45:14.083 回答