Current Location: Home> Latest Articles> How to Use the imagefontwidth() Function to Automatically Calculate Multi-line Text Layout for Easier Text Alignment?

How to Use the imagefontwidth() Function to Automatically Calculate Multi-line Text Layout for Easier Text Alignment?

M66 2025-06-30

In PHP, when dealing with image text layout, you often encounter problems with aligning multi-line text. The imagefontwidth() function from the GD library makes it easy to obtain the width of characters for a specific font, thus allowing for more precise text layout and alignment. This article will provide a detailed guide on how to use the imagefontwidth() function to automatically calculate the width of multi-line text, assisting with neat text alignment.

What is the imagefontwidth() Function?

imagefontwidth() is a function provided by the GD library that retrieves the width of each character in a specified built-in font, measured in pixels. The function prototype is as follows:

int imagefontwidth(int $font);

The parameter $font specifies the font size, with a range typically from 1 to 5, corresponding to the five built-in font sizes in GD.

The function returns the width of each character in that font.

With this function, you can determine the number of pixels each character occupies, allowing you to calculate the width of a whole line of text based on the string length.

Challenges of Multi-line Text Layout

Suppose you want to draw multi-line text on an image and have each line centered or left-aligned. Multi-line text typically has varying lengths, and simply calculating the width of the string and drawing it may result in uneven layout, especially when using monospaced fonts.

The solution is to first use imagefontwidth() to calculate the width of individual characters, then combine the string length to calculate the width of each line, and finally determine the starting coordinates of the text for automatic alignment.

Example Code: Automatically Calculating the Width of Multi-line Text and Drawing It

The following example code demonstrates how to use PHP's GD library together with imagefontwidth() to achieve center alignment for multi-line text:

<?php
// Create a blank image
$width = 400;
$height = 200;
$image = imagecreatetruecolor($width, $height);
<p>// Set background color and text color<br>
$bgColor = imagecolorallocate($image, 255, 255, 255); // White background<br>
$textColor = imagecolorallocate($image, 0, 0, 0);     // Black text</p>
<p>// Fill background<br>
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);</p>
<p>// Multi-line text to be drawn<br>
$textLines = [<br>
"This is the first line",<br>
"The second line is a bit longer",<br>
"Third line"<br>
];</p>
<p>// Choose font size<br>
$font = 5; // GD built-in font, between 1-5</p>
<p>// Calculate font width and height<br>
$fontWidth = imagefontwidth($font);<br>
$fontHeight = imagefontheight($font);</p>
<p>// Initial Y-coordinate for drawing<br>
$startY = 20;</p>
<p>// Loop through each line of text, calculate width and draw centered<br>
foreach ($textLines as $line) {<br>
$lineLength = strlen($line); // Note: strlen is for pure English text. Use mb_strlen for Chinese and ensure proper encoding<br>
$lineWidth = $fontWidth * $lineLength;</p>
$x = ($width - $lineWidth) / 2;

// Draw the text
imagestring($image, $font, $x, $startY, $line, $textColor);

// Update Y-coordinate for next line
$startY += $fontHeight + 10; // Line height 10 pixels

}

// Output the image
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>

Explanation of the Code:

  • Using imagefontwidth() and strlen() to calculate the width of the current line of text;

  • Calculating the X-coordinate for center alignment by subtracting the text width from the image width and dividing by 2;

  • Drawing each line of text and adjusting the Y-coordinate to achieve line breaks;

  • Note the width calculation for Chinese text. strlen() counts bytes, which may cause calculation errors. It's recommended to use mb_strlen() with appropriate character encoding.

How to Handle Width Calculation for Chinese Text?

imagefontwidth() can only retrieve the width of single characters, but Chinese characters are typically multi-byte. To ensure accuracy, it is best to use mb_strlen():

$lineLength = mb_strlen($line, 'UTF-8');

Make sure the PHP file and environment support UTF-8 encoding.

Conclusion

The imagefontwidth() function is a simple yet highly useful tool in PHP's GD library, helping developers automatically calculate the width of multi-line text and achieve more reasonable text layout and alignment. By combining string length and calculating the pixel width of each line of text, you can easily center-align or apply other alignment methods, greatly simplifying the complexity of image text handling.