簡體   English   中英

使用PHP GD將變量文本定位在標簽下居中

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

我已經使用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位數字出現在同一位置。

框大小調整給了我奇怪的結果,因此我通過創建一個函數來解決此問題,該函數計算每個數字中的位數並向后發送一個位置變量。

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