<?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);
?>
ImageCreatetrueColor()を使用して、指定された幅と高さの空白のキャンバスを作成します。
色を設定します:
ImageColorAllocate()を使用して、それぞれ背景とテキストに色の値を割り当てます。
背景の色を埋める:
ImageFilledRectangle()を使用して、レイヤー全体を黒に記入して、一般的な弾幕の背景をシミュレートします。
テキストコンテンツとフォントを設定します。
表示されるテキストのいくつかの段落を定義し、PHP内蔵フォント(番号1-5)を選択します。 imagettftext()を使用している場合は、カスタムTTFフォントファイルをサポートすることもできます。
テキストの幅を計算します:
ImageFontWidth()現在のフォント内の各文字のピクセル幅を返します。 strlen()と組み合わせて、テキスト全体の必要な幅を計算できます。
テキストを描く:
Imagestring()は、テキストを描画し、キャンバス上の適切な位置に配置するために使用されます。右から入る弾幕の効果をシミュレートするために、異なるXオフセットを設定します。
画像を出力してリソースを破壊します。
ImagePng()を使用してPNG画像を出力し、 Imagedestroy()を使用してリソースをリリースします。