views:

379

answers:

2

I am setting up dynamic forum signature images for my users and I want to be able to put their username on the image. I am able to do this just fine, but since usernames are different lengths and I want to right align the username, how can I go about doing this when I have to set x & y coordinates.

$im = imagecreatefromjpeg("/path/to/base/image.jpg");
$text = "Username";
$font = "Font.ttf";
$black = imagecolorallocate($im, 0, 0, 0);

imagettftext($im, 10, 0, 217, 15, $black, $font, $text);
imagejpeg($im, null, 90);
+1  A: 

Pre-calculate the size of the user's name using imagettfbbox().

From the width you get from there, you can then deduct the x position at which your text needs to start.

Pekka
+1  A: 

Use the imagettfbbox function to get the width of the string and then subtract that from the width of the image to get the starting x-coordinate.

$dimensions = imagettfbbox($fontSize, $angle, $font, $text);
$textWidth = abs($dimensions[4] - $dimensions[0]);
$x = imagesx($im) - $textWidth;
Andy Shea