Current Location: Home> Latest Articles> Use imagefontwidth() to create barrage text layers

Use imagefontwidth() to create barrage text layers

M66 2025-05-28

<?php // 设置内容类型为图像 header('Content-Type: image/png'); // 创建画布 $width = 800; $height = 100; $image = imagecreatetruecolor($width, $height); // 定义颜色 $backgroundColor = imagecolorallocate($image, 0, 0, 0); // 黑色背景 $textColor = imagecolorallocate($image, 255, 255, 255); // 白色文字 // 填充背景 imagefilledrectangle($image, 0, 0, $width, $height, $backgroundColor); // 要显示的弹幕文字 $danmuTexts = [ "欢迎来到m66.net!", "PHP制作弹幕图层演示", "让文字飞一会儿~" ]; // 使用内置字体编号(1-5) $font = 5; // 获取字体的宽度与高度 $charWidth = imagefontwidth($font); $charHeight = imagefontheight($font); // 初始Y位置 $y = 10; // 循环绘制每条弹幕 foreach ($danmuTexts as $index => $text) { // 计算文字总宽度 $textWidth = strlen($text) * $charWidth; // 设置X位置为图像右侧外边界,用于模拟从右向左滚动 $x = $width - ($index * 50); // 模拟不同起始偏移 // Y位置随行数递增 $textY = $y + $index * ($charHeight + 5); // 绘制文字 imagestring($image, $font, $x, $textY, $text, $textColor); } // 输出图像 imagepng($image); imagedestroy($image); ?>


Steps detailed explanation:


  1. Use imagecreatetruecolor() to create a blank canvas with a specified width and height.

  2. Set the color:
    Use imagecolorallocate() to assign color values ​​to the background and text respectively.

  3. Fill background color:
    Use imagefilledrectangle() to fill the entire layer into black to simulate common barrage backgrounds.

  4. Set text content and font:
    Define the few paragraphs of text to be displayed and select the PHP built-in font (number 1-5). If you are using imagettftext(), you can also support custom TTF font files.

  5. Calculate text width:
    imagefontwidth() returns the pixel width of each character in the current font. Combined with strlen() , you can calculate the required width of the entire text.

  6. Draw text:
    imagestring() is used to draw text and place it in the appropriate position on the canvas. We set different X offsets to simulate the effect of the barrage entering from the right.

  7. Output the image and destroy the resource:
    Use imagepng() to output PNG images, and then use imagedestroy() to release resources.