Jump to content

[SOLVED] centering text with GD


Renlok

Recommended Posts

how can i center the text with GD this is what ive got at the moment as it puts it in the top right corner

<?php
// set dimensions
     if($_GET['w'] == 0 || $_GET['w'] == ""){
	 $w = 102;
 } else {
 	$w = $_GET['w'];
     }
 if($_GET['h'] == 0 || $_GET['h'] == ""){
	 $h = 13;
 } else {
 	$h = $_GET['h'];
     }
// create image
     $im = imagecreate($w, $h);
// set colours to be used
     $bg = imagecolorallocate($im, 0xE0, 0xE0, 0xE0);
     $black = imagecolorallocate($im, 0x00, 0x00, 0x00);
     $barcolor  = imagecolorallocate($im, 0xFF, 0x00, 0x00);
// draw border
     imagerectangle($im, 0,0,$w-1,$h-1,$black);
// get value and max value from query string
     $val = isset($_GET['val']) ? $_GET['val'] : 0;
     $max = isset($_GET['max']) ? $_GET['max'] : 100; 
// calculate dimensions of inner bar
     $barw = $max ? floor(($w-1) * $val / $max) : 0;
     $barh = $h - 1;
// draw inner bar
 if ($barw)
     	imagefilledrectangle($im, 1, 1, $barw, $barh, $barcolor);
//add tone to image so its no longer flat
     $imgw = $barw + 1;
 $im2 = imagecreate($imgw, $barh);
 imagepng($im2, "images/bargrad.png");
 imagecopymerge($im, $im2, 0, 0, 0, 0, $imgw, $barh, 25);
 $im3 = imagecreate($imgw, 2);
 imagegif($im3, "images/wspacer.gif");
 imagecopymerge($im, $im3, 0, 2, 0, 0, $imgw, $barh, 35);
//get the fonts
 $font_size=8;
 putenv('GDFONTPATH=/home/renlok/public_html/rpforum/fonts'); //the fonts path
 $font_type='KABOB';
 $text="$val/$max";
 $bbox=imagettfbbox($font_size, 0, $font_type, $text);
 $right_text = $bbox[2];
 $left_text = $bbox[0];
 $width_text = $left_text - $right_text;
 $height_text = abs($bbox[7] - $bbox[1]);
 $text_x = $w/2 - $width_text/2;
 $text_y = $h/2 - $height_text/2;


 $above_line_text = abs($bbox[7]);   // how far above the baseline?
 $text_y += $above_line_text;        // add baseline factor 
 $text_y -= 2;  // adjustment factor for shape of our template


 imagettftext($im, $font_size, 0, $text_x, $text_y, $black, $font_type, $text);
// send image header
     header("content-type: image/png");
// send png image
     imagepng($im);
     imagedestroy($im);
?>

Link to comment
https://forums.phpfreaks.com/topic/54654-solved-centering-text-with-gd/
Share on other sites

I've been trying to figure this one out myself as I've made a nice website to make amusing random signature images.

 

Seems the GD support for TTF files doesn't have a fnction to calculate the width of text unlike bitmapped fonts.

 

I'm hoping I'm wrong...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.