简体   繁体   English

使用PHP GD将变量文本定位在标签下居中

[英]Position variable text centered under label using PHP GD

I have successfully outputted text (consisting of 2-3 digit numbers) onto an image using the PHP GD imaging library. 我已经使用PHP GD映像库成功地将文本(由2-3位数字组成)输出到图像上。 Next I would like to position this text and center it under labels included in the image. 接下来,我想定位此文本并将其居中放置在图像中包含的标签下。 I have it working now by looking at the image and hardcoding position values, but this is not ideal as the numbers vary and may not be the same length each time the code is run. 我现在通过查看图像和硬编码位置值来使它工作,但这并不理想,因为数字各不相同,每次运行代码时长度可能都不相同。

Here is a simplified version of what I have so far: 这是到目前为止的简化版本:

<?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);

?>

I believe that I need to use imagettfbbox, but how do I position the box according to the label in the image? 我相信我需要使用imagettfbbox,但是如何根据图像中的标签放置盒子呢?

Is it possible to set a primary position for each label (as they will never move) and center according to that no matter the length of the number? 是否可以为每个标签设置一个主要位置(因为它们永远不会移动)并根据该位置居中,而不管编号的长度如何? For example, if a 4 digit number was entered it would appear in the same place as a 2 digit number centered under its label. 例如,如果输入了4位数字,则它将与位于其标签下方的2位数字出现在同一位置。

Box sizing was giving me strange results, so I solved this by creating a function that calculates the number of digits in each number and sends a position variable back. 框大小调整给了我奇怪的结果,因此我通过创建一个函数来解决此问题,该函数计算每个数字中的位数并向后发送一个位置变量。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM