代码之家  ›  专栏  ›  技术社区  ›  Morten Hagh

foreach循环x坐标中的图像复制

  •  1
  • Morten Hagh  · 技术社区  · 13 年前

    我有一个图像函数,我有一点问题

    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个像素的foreach中?

    next image in the loop:    
    imagecopy($img, $cur, previous_x_coord+100, 0, 0, 0, 125, 32);
    
    2 回复  |  直到 13 年前
        1
  •  1
  •   Michael Berkowski    13 年前

    只需存储一个从零开始并在每次循环迭代结束时加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;
        }
    
        2
  •  1
  •   Elias Van Ootegem    13 年前

    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行代码,也不需要额外变量。批评者可能会说这个代码 维护性较差 ,在这种情况下,我会说:“那就不要忍者评论了。”

    警告:
    正如Michael所指出的,由于明显的原因,此代码无法与关联数组一起使用( 'First_Key'*100 === ? )