Page 1 of 1
GD Text align help
Posted: Sat May 13, 2006 12:53 am
by _qwerty_
Hey experts,
I got a question, in GD is there a possibility to align text to the center, so when you create a image, the text will be in the center no matter how long it is, i searched on google, and you need a module for that, so i was wondering is there is another way to do it.
thanks

Re: GD Text align help
Posted: Sat May 13, 2006 1:04 am
by _qwerty_
a?

Posted: Sat May 13, 2006 6:07 am
by onion2k
You'll need to calculate the center point using either fontwidth() if you're using imagestring() for the text, imagettfbbox() if you're using imagettftext() .. or one of the other bounding box functions if you're using something else to draw the text.
Basically what you'll need to do is:
Calculate the width of the string using imagettfbbox().
Subtract the width of the string from the width of the image.
Divide the result of that by 2.
Draw the text that distance from the left side of the image.
Posted: Sat May 13, 2006 7:20 am
by _qwerty_
Can you make me an a example of that GD script...
I'm just started learning GD
i just did a
<?php
header("Content-type: image/Gif");
$src_file = "button.gif";
$src = @ImageCreateFromGif($src_file) or die("error!");
$txt = ImageColorAllocate($src, 250, 20, 10);
ImageString($src, 10, 0, 0,"text",$txt);
ImageGif($src);
ImageDestroy($src);
?>
Posted: Sat May 13, 2006 7:58 am
by jayshields
he's just telling you how to work out where to start the text from.
it's just simple logic. i've never used GD before, but I presume he's telling you to work out which pixel is the centre pixel by getting the total width, and halving it (call this value 1). then get the text string total width, half that (call this value 2). subtract value 2 from value 1 and you have the pixel to start from.
Posted: Sat May 13, 2006 8:12 am
by onion2k
Code: Select all
<?php
header("Content-type: image/Gif");
$src_file = "button.gif";
$src = @ImageCreateFromGif($src_file) or die("error!");
$txt = ImageColorAllocate($src, 250, 20, 10);
//New code
$string = "text";
$font = 10;
$image_width = imagesx($src);
$string_width = imagefontwidth($font)*strlen($string);
$string_x_position = ($image_width-$string_width)/2;
$image_height = imagesy($src);
$string_height = imagefontheight($font);
$string_y_position = ($image_height-$string_height)/2;
ImageString($src, $font, $string_x_position, $string_y_position,$string,$txt);
//End of new code
//ImageString($src, $font, $string_x_position, 0,$string,$txt);
ImageGif($src);
ImageDestroy($src);
?>
I haven't tested it.
Posted: Sat May 13, 2006 9:09 am
by _qwerty_
thanks
