PHPでは、 Imagestringup()関数を使用して、画像に文字列を垂直に描画します。 Imagestring()に似ていますが、描画されたテキストは垂直方向に上方になります。これは、回転テキスト効果で画像を生成するときに非常に実用的です。ただし、 Imagestringup()を使用してテキストを直接描画する場合、テキストのレイアウトとアラインメントには、開発者による手動制御が必要になることがよくあります。この時点で、画像FontWidth()関数は、文字幅を正確に計算するのに役立つため、テキストのレイアウトとアライメントをより適切に調整するのに役立ちます。
Imagestringup()
画像の上に文字列を垂直に描画するために使用される構文は次のとおりです。
bool imagestringup(resource $image, int $font, int $x, int $y, string $string, int $color);
その中で、 $ fontは組み込みのフォントサイズ(1〜5)、 $ x、$ yは開始座標、 $文字列はテキストコンテンツ、 $ colorはカラーリソースです。
ImageFontWidth()
指定された内蔵フォントサイズの文字幅を返します。構文は次のとおりです。
int imagefontwidth(int $font);
これら2つの関数を使用すると、描画時にテキストの位置を制御でき、重複するテキストまたは不規則なレイアウトを回避できます。
Imagestringup()はテキストを垂直に描画するため、各文字の水平間隔は固定されていますが、文字幅が計算されず、座標図が直接与えられた場合、特に複数の線が描画または中心的なアライメントが必要な場合、テキストは予想される位置から逸脱する場合があります。したがって、最初にimageFontWidth()を介してフォントの文字幅を取得し、各文字の描画位置を計算し、合理的なテキストレイアウトを確認する必要があります。
200ピクセルの幅の画像で、弦の線を垂直に描画し、水平の中心アライメントを実現したいとします。
<?php
// 空白の画像を作成します
$width = 200;
$height = 100;
$image = imagecreatetruecolor($width, $height);
// 色を割り当てます
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
// 背景の色を埋めます
imagefill($image, 0, 0, $white);
$text = "Hello";
$font = 5; // 内蔵フォントサイズ 1~5
// テキスト幅を計算します
$fontWidth = imagefontwidth($font);
$textWidth = strlen($text) * $fontWidth;
// 計算開始 x 座標,センターレベルを達成します
$x = ($width - $textWidth) / 2;
// y 座標从底部开始向上绘制
$y = 80;
// 使用 imagestringup() 垂直テキストを描きます
imagestringup($image, $font, $x, $y, $text, $black);
// 出力画像
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
ImageFontWidth($ font)でフォントの各文字の幅を取得します。
文字列の長さを掛けて、全体的なテキスト幅を取得します。
テキストの幅を画像幅で減算し、それを2で除算して、テキストを水平に中心にします。
Imagestringup()の座標では、 xはテキストの左端であり、 yはテキストの下部にあるベースラインの垂直座標です。
左から右に配置された複数のテキストセグメントを描画するなど、複数の垂直テキストを描画する必要がある場合、各セグメントが垂直に表示される場合、 ImageFontWidth()を使用して各セグメントの幅を計算し、X座標を動的に調整することもできます。
<?php
$width = 300;
$height = 150;
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefill($image, 0, 0, $white);
$font = 4;
$texts = ["PHP", "Imagestringup", "Example"];
// 総幅を計算します
$fontWidth = imagefontwidth($font);
$totalWidth = 0;
foreach ($texts as $t) {
$totalWidth += strlen($t) * $fontWidth + 10; // 各間隔10ピクセル
}
$totalWidth -= 10; // 最後のものは間隔ではありません
// 始める x 座標居中
$x = ($width - $totalWidth) / 2;
$y = 130;
foreach ($texts as $t) {
imagestringup($image, $font, $x, $y, $t, $black);
$x += strlen($t) * $fontWidth + 10;
}
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
これにより、複数の垂直テキストの配置とアラインメントを柔軟に制御できます。