From 7d6dc1c4cd31096bc8079fa7b34973692bdb0e30 Mon Sep 17 00:00:00 2001 From: Sven Olderaan Date: Sun, 16 Mar 2025 16:17:34 +0100 Subject: [PATCH] Center text horizontally and vertically in bubbles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add horizontal centering for each line of text - Add vertical centering for the entire text block - Ensure text doesn't overflow the top of the bubble - Maintain compatibility with both built-in and TTF fonts 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- image.php | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/image.php b/image.php index aeebeca..c128ce1 100644 --- a/image.php +++ b/image.php @@ -336,16 +336,37 @@ if ($currentLine !== '') { $lines[] = $currentLine; } +// Center text vertically in the bubble +$lineCount = count($lines); +if (isset($config['use_builtin_font'])) { + $totalTextHeight = $lineCount * imagefontheight(5); +} else { + $totalTextHeight = $lineCount * $config['line_height']; +} + +// Calculate vertical starting position for centered text +$startY = $textAreaY + ($textAreaHeight - $totalTextHeight) / 2; +if ($startY < $textAreaY) $startY = $textAreaY; // Ensure text doesn't overflow top + // Draw text -$y = $textAreaY + $config['font_size']; // Start position for text +$y = $startY + $config['font_size']; // Start position for centered text foreach ($lines as $line) { if (isset($config['use_builtin_font'])) { + // Calculate width for centering horizontally + $lineWidth = imagefontwidth(5) * strlen($line); + $x = $textAreaX + ($textAreaWidth - $lineWidth) / 2; + // Use built-in font (less nice but always available) - imagestring($canvas, 5, $textAreaX, $y, $line, $textColor); + imagestring($canvas, 5, $x, $y, $line, $textColor); $y += imagefontheight(5); } else { + // Calculate width for centering horizontally + $bbox = imagettfbbox($config['font_size'], 0, $config['font'], $line); + $lineWidth = $bbox[2] - $bbox[0]; + $x = $textAreaX + ($textAreaWidth - $lineWidth) / 2; + // Use TrueType font (nicer but requires font file) - imagettftext($canvas, $config['font_size'], 0, $textAreaX, $y, $textColor, $config['font'], $line); + imagettftext($canvas, $config['font_size'], 0, $x, $y, $textColor, $config['font'], $line); $y += $config['line_height']; } }