update page now

Voting

: three plus four?
(Example: nine)

The Note You're Voting On

james dot heazlewood at crownbet com au
8 years ago
I found the bounding boxes a bit tricky to use when trying to rotate AND align text boxes. I wrote this function allows you to set left, right or center aligned text and also rotate it.

<?php
  /**
   * Renders rotate-able and align-able text of any font or colour
   * 
   * @param resource $img Image resource
   * @param string $text
   * @param int $x
   * @param int $y
   * @param int $fontSize
   * @param string $fontFile Full path to font file
   * @param array $color Red, green, blue values in either int (255) or hex (0xFF)
   * @param string $align Accept 'left', 'right', and defaults to center
   * @return void
   */
  function gd_text_aligned($img, $text, $x, $y, $fontSize, $fontFile, $color = [0, 0, 0], $align = 'left') {

      // Create colour Resource
      $textColor = imagecolorallocate($img, $color[0], $color[1], $color[2]);

      // Create bounding box co-ordinates
      $boundingBox = imagettfbbox($fontSize, $rotation, $fontFile, $text);
      $textBox = imagettfbbox($fontSize, 0, $fontFile, $text);

      //  Bounding box array key meanings
      //
      //  $bBox[0] = lower left  X
      //  $bBox[1] = lower left  Y
      //  $bBox[2] = lower right X
      //  $bBox[3] = lower right Y
      //  $bBox[4] = upper right X
      //  $bBox[5] = upper right Y
      //  $bBox[6] = upper left  X
      //  $bBox[7] = upper left  Y
      //
      //     6,7     |     4,5
      //        -----+-----
      //     0,1     |     2,3
      //
      $boundingBoxWidth = $boundingBox[4] - $boundingBox[0];
      $boundingBoxHeight = $boundingBox[5] - $boundingBox[1];
      $flatHeight = $textBox[5] - $textBox[1]; 

      // Align left right or centred?
      if($align == 'left') {
          $drawX = $x - sin($rotation * M_PI / 180) * ($flatHeight / 2);
          $drawY = $y - cos($rotation * M_PI / 180) * ($flatHeight / 2);
      } else if($align == 'right') {
          $drawX = $x - $boundingBoxWidth + sin($rotation * M_PI / 180) * ($flatHeight / 2);
          $drawY = $y - $boundingBoxHeight + cos($rotation * M_PI / 180) * ($flatHeight / 2);
      } else {
          // no alignment (centred)
          $drawX = $x - $boundingBoxWidth / 2;
          $drawY = $y - $boundingBoxHeight / 2;
      }
      
      // draw text
      imagettftext(
          $img,
          $fontSize,
          $rotation, $drawX, $drawY,
          $textColor, $fontFile, $text
      );
      
    }

<< Back to user notes page

To Top