【问题标题】:Position variable text centered under label using PHP GD使用 PHP GD 在标签下居中定位变量文本
【发布时间】:2016-11-16 11:07:57
【问题描述】:

我已经使用 PHP GD 图像库成功地将文本(由 2-3 位数字组成)输出到图像上。接下来,我想定位此文本并将其置于图像中包含的标签下方。我现在通过查看图像和硬编码位置值来使其工作,但这并不理想,因为数字会有所不同,并且每次运行代码时的长度可能都不相同。

这是我目前所拥有的简化版本:

<?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 位数字出现在同一位置。

【问题讨论】:

标签: php image-processing gd imagettftext


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2023-03-30
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多