2010-09-09 82 views
6

我使用imagettftext做出條形圖,並在頂部各條我想把PHP GD ttftext居中對齊

我會爲每個欄的以下變量(這是真正的矩形)

$x1 $y1 $x2 $y2 $imagesx $imagesy $font_size

此外,字號應該減少爲字符串長度增加。

alt text

+1

男孩,你是在爲一些工作!它有*是PHP嗎?有這樣好的(和現成的)JavaScript繪圖庫在那裏... – 2010-09-09 18:50:10

+0

我在做一個PHP庫,所以... – 2010-09-09 18:53:50

+0

會很高興有「爲樣品製作條形碼」代碼,你可以發佈它嗎? – Otar 2010-09-14 06:48:44

回答

11

這樣做。請記住字體文件「ARIAL.TTF」放置在當前目錄下:

<?php 
// Create a 650x150 image and create two colors 
$im = imagecreatetruecolor(650, 150); 
$white = imagecolorallocate($im, 255, 255, 255); 
$black = imagecolorallocate($im, 0, 0, 0); 

// Set the background to be white 
imagefilledrectangle($im, 0, 0, 649, 149, $white); 

// Path to our font file 
$font = './arial.ttf'; 

//test it out 
for($i=2;$i<10;$i++) 
    WriteTextForMe($im, $font, str_repeat($i, $i), -140 + ($i*80), 70 + rand(-30, 30), -160 + (($i+1)*80), 150, $black); 

//this function does the magic 
function WriteTextForMe($im, $font, $text, $x1, $y1, $x2, $y2, $allocatedcolor) 
{ 
    //draw bars 
    imagesetthickness($im, 2); 
    imagerectangle($im, $x1, $y1, $x2, $y2, imagecolorallocate($im, 100,100,100)); 

    //draw text with dynamic stretching 
    $maxwidth = $x2 - $x1; 
    for($size = 1; true; $size+=1) 
    { 
     $bbox = imagettfbbox($size, 0, $font, $text); 
     $width = $bbox[2] - $bbox[0]; 
     if($width - $maxwidth > 0) 
     { 
      $drawsize = $size - 1; 
      $drawX = $x1 + $lastdifference/2; 
      break; 
     } 
     $lastdifference = $maxwidth - $width; 
    } 
    $size--; 
    imagettftext($im, $drawsize, 0, $drawX, $y1 - 2, $allocatedcolor, $font, $text); 
} 

// Output to browser 
header('Content-type: image/png'); 

imagepng($im); 
imagedestroy($im); 
?> 

它使用imagettfbbox函數來獲取文本的寬度,然後循環在字體大小以獲得正確的大小,其中心並顯示它。

因此,它輸出以下:

alt text

2

您可以通過計算你的文本的中心PHP的imagettfbbox-function

// define text and font 
$text = 'some bar label'; 
$font = 'path/to/some/font.ttf'; 

// calculate text size (this needs to be adjusted to suit your needs) 
$size = 10/(strlen($text) * 0.1); 

// calculate bar center 
$barCenter = $x1 + ($x2 - $x1)/2; 

// calculate text position (centered) 
$bbox = imagettfbbox($size, 0, $font, $text); 
$textWidth = $bbox[2] - $bbox[0]; 
$positionX = $textWidth/2 + $barCenter; 
$positionY = $y1 - $size; 

編輯:更新的代碼來完成所有的工作適合你。

+0

如何正確*你會用它來得到寫它的地方,所以它變得居中 – 2010-09-09 18:01:29

+0

我相應地編輯了我的帖子。該代碼計算給定文本的中心對齊位置「$ positionX」。 – jwueller 2010-09-09 18:27:41

+0

嗯,讓我重新寫下這個問題 – 2010-09-09 18:45:37