2016-07-13 49 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);