在PHP GD脚本中绘制文本背景色

在PHP GD脚本中绘制文本背景色,php,gd,Php,Gd,我试图用不同的颜色、字体和文本背景在图像中书写文本。对于绘图文本背景,我使用“imagefilledrectangle”函数。目前,脚本为foreach循环中的每行文本绘制背景文本颜色 现在,我有两个不同的要求 (1) 脚本必须仅在循环的第一次和最后一次迭代中绘制背景文本颜色或矩形。换句话说,我只需要第一个和最后一个文本数组的背景文本颜色,而不需要中间的文本 (2) 脚本必须在循环的每次迭代中生成文本背景色,第一次和最后一次除外。换句话说,我不需要只在第一个和最后一个数组文本中使用文本背景色 我

我试图用不同的颜色、字体和文本背景在图像中书写文本。对于绘图文本背景,我使用“imagefilledrectangle”函数。目前,脚本为foreach循环中的每行文本绘制背景文本颜色

现在,我有两个不同的要求

(1) 脚本必须仅在循环的第一次和最后一次迭代中绘制背景文本颜色或矩形。换句话说,我只需要第一个和最后一个文本数组的背景文本颜色,而不需要中间的文本

(2) 脚本必须在循环的每次迭代中生成文本背景色,第一次和最后一次除外。换句话说,我不需要只在第一个和最后一个数组文本中使用文本背景色

我需要一个办法

这是完整的脚本

<?php

        $user = array(

        array(
            'name'=> 'Ashley Ford', 
            'font-size'=>'27',
            'color'=>'grey'),

        array(
            'name'=> 'Technical Director',
            'font-size'=>'16',
            'color'=>'grey'),

        array(
            'name'=> 'ashley@papermashup.com',
            'font-size'=>'13',
            'color'=>'green'
            )

    );

       function center_text($text, $size)
    {
        global $fontfile;
        global $image;
        // calculate position of text
        $tsize = imagettfbbox($size, 0, $fontfile, $text);
        $text_h = $tsize[7];
        $dx = abs($tsize[2] - $tsize[0]); // how wide is the text?
        $dy = abs($tsize[5] - $tsize[3]); // how tall is the text?
        $x = (imagesx($image) - $dx)/2;
        $y = (imagesy($image) - $dy)/2 + $dy;
        return array($dx, $text_h, $x, $y);
    }

    // link to the font file 
    $fontfile = 'XBall.ttf';

    // controls the spacing between text
    $i = 30;

    //JPG image quality 0-100
    $quality = 90;

    // Loan an existing image
    $image = imagecreatefromjpeg('weight-loss.jpg');

    // setup the text colors
    $color['grey'] = imagecolorallocate($image, 54, 56, 60);
    $color['green'] = imagecolorallocate($image, 55, 189, 102);

    $white = imagecolorallocate($image, 255, 255, 255);

    // this defines the starting height for the text block
    // $y = imagesy($image) - 365;

    // loop through the array and write the text
    foreach ($user as $value)
    {
        list($dx, $text_h, $x, $y) = center_text($value['name'], $value['font-size']);
        // Draw text background
        imagefilledrectangle($image, $x, $y + $text_h + $i, $x + $dx, $y + $i, $white);
        // Draw text
        imagettftext($image, $value['font-size'], 0, $x, $y + $i, $color[$value['color']], $fontfile, $value['name']);

        // add 32px to the line height for the next text block
        $i = $i+32;
    }

    header ('Content-Type: image/jpeg');
    imagejpeg($image);




?>