PHPで文字列を正しい位置に印字する関数

PHPで画像を生成する際、文字列を印字するにはimagettftextを使いますが、位置が微妙にずれます。
これを解消する関数を自作しました。

function position_text($image, $size, $x, $y, $color, $font_filename, $text, $oriental, $vertical){
  //$oriental=left,center,rightを指定。
  //$vertical=top,middle,bottomを指定。
  //left,bottomとすると左下を基準とする。
  //center,middleとすると上下左右の中心を基準とする。
  $angle = 0;
  $pos = imagettfbbox($size, $angle, $font_filename, $text);
  $width = $pos[2] - $pos[0];
  $height = $pos[3] - $pos[7];
  if($oriental == "center"){
    $x = $x - $width * 0.5;
  }else if($oriental == "right"){
    $x = $x - $width;
  }
  if($vertical == "middle"){
    $y = $y + $height * 0.5;
  }else if($vertical == "top"){
    $y = $y + $height;
  }
  imagettftext($image, $size, $angle, $x - $pos[0], $y - $pos[3], $color, $font_filename, $text);
}

コメント

タイトルとURLをコピーしました