2015-05-07 124 views

回答

0

這是代碼,但我不需要將整個框對齊到X軸上的右側,但是隻有文字。你可以像它一樣的文字是HTML

<p style="width:300px;text-align:right">This is the text to be wrapped and aligned to the right</p> 

function wrap($fontSize, $angle, $fontFace, $string, $width){ 

    $ret = ""; 
    $arr = explode(' ', $string); 
    foreach ($arr as $word){ 
     $teststring = $ret.' '.$word; 
     $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring); 
     if ($testbox[2] > $width){ 
      $ret.=($ret==""?"":"\n").$word; 
     } else { 
      $ret.=($ret==""?"":' ').$word; 
     } 
    } 
    return $ret; 
} 

function textToImage(){ 
    $pluginDir = plugin_dir_path(__FILE__); 
    $image = imagecreatefrompng($pluginDir . 'resources/img/image.png'); 
    $color = imagecolorallocate($image, 38, 64, 142); 
    $font_path = $pluginDir . 'resources/font/DroidSans.ttf'; 
    $line = "This is the text to be wrapped and aligned to the right"; 

    imagettftext($image, 35, 0, 300, 600, $color, $font_path, wrap(18, 0, $font_path, $line, 300)); 

    imagepng($image, $pluginDir."resources/img/result.png"); 
    imagedestroy($image); 
} 
+0

任何幫助傢伙?我越來越絕望了。 – Jamalissimo

0

您可以使用stil/gd-text類。它爲你做了正確的對齊和文字包裝。

<?php 
use GDText\Box; 
use GDText\Color; 

$pluginDir = plugin_dir_path(__FILE__); 
$image = imagecreatefrompng($pluginDir . 'resources/img/image.png'); 

$textbox = new Box($image); 
$textbox->setFontSize(35); 
$textbox->setFontFace($pluginDir . 'resources/font/DroidSans.ttf'); 
$textbox->setFontColor(new Color(38, 64, 142)); 
$textbox->setBox(
    300, // distance from left edge 
    600, // distance from top edge 
    500, // textbox width 
    500 // textbox height 
); 

// now we have to align the text horizontally and vertically inside the textbox 
$textbox->setTextAlign('top', 'right'); 
// it can wrap multilined text 
$textbox->draw("This is the text to be wrapped and aligned to the right"); 

imagepng($image, $pluginDir."resources/img/result.png"); 
imagedestroy($image); 

示範:

demo