2011-12-21 31 views
2

我試圖使用PHP創建一個透明文本框的圖像與最大。 2行文字。盒子寬度固定爲90px;高度根據所包含的文本而變化(同樣,文本可能佔用1到2行):examplePHP:創建圖像框,其高度取決於其包含的文本

我認爲最具挑戰性的部分是如何根據文本長度「自動」設置框高度。也就是說,該腳本應該足夠智能以便:

  1. 如果長度超過寬度,則將文本(第2行)換行。
  2. 調整框高度,因爲現在有兩條線。

假設文本總是適合一行和箱體,該腳本可以相當簡單:

<?php 
$im = imagecreatetruecolor(90, 22); 
$white = imagecolorallocate($im, 255, 255, 255); 
$blue = imagecolorallocate($im, 92, 149, 167); 

// Set the background to be blue 
imagefilledrectangle($im, 0, 0, 90, 22, $blue); 

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

imagefttext($im, 10, 0, 5, 15, $white, $font, "Barton Hotel"); 

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

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

回答

0

使用imagettfbox獲得文字的邊框,並利用這些信息來實際生成的框。

我有這個功能來生成文字圖片:

function generate_words($word) 
{ 
    $fontSize = 10; 
    $fontFile = dirname(__FILE__) . '/fonts/verdana.ttf'; 
    $boundingBox = imagettfbbox($fontSize, 0, $fontFile, $word); 
    $imageWord = imagecreate(abs($boundingBox[2]) + abs($boundingBox[0]), abs($boundingBox[7]) + abs($boundingBox[1])); 
    $background = imagecolorallocate($imageWord, 255, 255, 255); 
    $black = imagecolorallocate($imageWord, 0, 0, 0); 
    imagettftext($imageWord, $fontSize, 0, 0, abs($boundingBox[5]), $black, $fontFile, $word); 
    //print_r($boundingBox); 

    return $imageWord;  
} 

使用方法如下:

$imageWord = generate_words("my text"); 
$imageWordWidth = imagesx($imageWord); 
$imageWordHeight = imagesy($imageWord); 

最後,結合生成的文本圖像資源爲基礎或背景圖片:

imagecopymerge($baseImage, $imageWord, $wordXLocationRelativeToBase, $wordYLocationRelativeToBase, 0, 0, $imageWordWidth, $imageWordHeight, 100); 
+1

也許我是缺乏瞭解邊界框是什麼:http://stackoverflow.com/q/8587301/583539。幫幫我? – moey 2011-12-21 09:07:00

+0

在那裏回答了你的問題 – ariefbayu 2011-12-21 11:05:32

相關問題