2016-07-13 52 views
0

我已經成功地使用PHP GD圖像庫將文本(由2-3位數字組成)輸出到圖像上。接下來,我想定位此文字並將其置於圖像中包含的標籤下方。我現在通過查看圖像和硬編碼位置值來開始工作,但這並不理想,因爲數字會有所不同,並且每次運行代碼時長度可能不同。位置變量文本位於標籤下使用PHP GD

這裏是我到目前爲止的簡化版本:

<?php 

$font  = 'arial.ttf'; 
$fontsize = 60; 

$value1 = $_GET['r']; 
$value2 = $_GET['rm']; 
$value3 = $_GET['w']; 

$image = imagecreatefrompng('image.png'); 

$fontcolor = imagecolorallocate($image, 255, 255, 255); 

$x1 = 80; 
$x2 = 160; 
$x3 = 280; 
$y = 1050; 

imagettftext($image, $fontsize, 0, $x1, $y, $fontcolor, $font, $value1); 
imagettftext($image, $fontsize, 0, $x2, $y, $fontcolor, $font, $value2); 
imagettftext($image, $fontsize, 0, $x3, $y, $fontcolor, $font, $value3); 

header('Content-type: image/png'); 
imagepng($image); 
imagedestroy($image); 

?> 

我相信,我需要使用imagettfbbox,但我怎麼根據圖像中的標籤位置的盒子?

是否有可能爲每個標籤設置一個主要位置(因爲他們永遠不會移動),並根據該位置居中,而不管數字的長度是多少?例如,如果輸入了一個4位數的數字,它將出現在與其標籤中間的2位數字相同的地方。

+0

http://php.net/imagettfbbox - 獲取盒子大小,使用計算定位。 –

回答

0

Box sizing是給我奇怪的結果,所以我解決了這個通過創建計算每個號碼位數,併發送一個位置可變回功能。

function position($value, $pos) { 
    $length = strlen((string)$value); 
    return $pos - (20 * $length); 
} 

$value1 = $_GET['r']; 
$value2 = $_GET['rm']; 
$value3 = $_GET['w']; 

$x1 = position($value1, 110); 
$x2 = position($value2, 310); 
$x3 = position($value3, 545); 
$y = 1050; 

imagettftext($image, $fontsize, 0, $x1, $y, $fontcolor, $font, $value1); 
imagettftext($image, $fontsize, 0, $x2, $y, $fontcolor, $font, $value2); 
imagettftext($image, $fontsize, 0, $x3, $y, $fontcolor, $font, $value3);