Andrei Oniga
Andrei Oniga

Reputation: 8559

How to control text alignment for text generated using `imagettftext()`?

Using the imagettftext function from the PHP GD library, one can only draw text that is left-aligned onto an image. At least so it would seem, perhaps I'm missing something.

How can I control the alignment of the text drawn onto an image? i.e. left / center / right (/ justified - not necessary, but useful)

I should mention that the alignment is visible when the drawn text contains multiple lines (e.g. "bla bla bla/nAnd another line of bla.").

Upvotes: 3

Views: 10452

Answers (3)

stil
stil

Reputation: 5556

You can use stil/gd-text class. Disclaimer: I am the author.

<?php
use GDText\Box;
use GDText\Color;

$img = imagecreatefromjpeg('image.jpg');

$textbox = new Box($img);
$textbox->setFontSize(12);
$textbox->setFontFace('arial.ttf');
$textbox->setFontColor(new Color(255, 255, 255));
$textbox->setBox(
    50,  // distance from left edge
    50,  // distance from top edge
    200, // textbox width
    100  // textbox height
);

// now we have to align the text horizontally and vertically inside the textbox
$textbox->setTextAlign('left', 'top');
// or like this:
// $textbox->setTextAlign('right', 'top');
// $textbox->setTextAlign('center', 'top');
// $textbox->setTextAlign('center', 'bottom');
// $textbox->setTextAlign('right', 'center');

// it accepts multiline text
$textbox->draw("text to write on picture\nanother line below");

Demonstration:

demo

Upvotes: 5

Joe Brown
Joe Brown

Reputation: 637

The function accepts x and y positional coordinates.

    array imagettftext ( resource $image, 
                         float $size, 
                         float $angle, 
                         int $x, 
                         int $y, 
                         int $color, 
                         string $fontfile, 
                         string $text )

Take a look at http://php.net/manual/en/function.imagettftext.php

Upvotes: 0

oezi
oezi

Reputation: 51797

with imagettftext() you're not writing into some kind of "box" but just at the given coordnates. to alingn the text properly, you'll have to calculate the correct coordinates to make it "look like" it's right-aligned or centered.

to do so, you can use imagettfbox() to get the size of your text - the rest is simple math:

  • to right-align add [textarea-width]-[textwidth] to your X-coordinate
  • to center add ([textarea-width]-[textwidth]) / 2 to your X-coordinate

(*textarea = the area you want to write the text at in your image - it's size should be known to you)

Upvotes: 7

Related Questions