2016-07-05 6 views
-1

Я хочу, чтобы текст был «Text Align Right».PHP: imagettftext text align right (RTL)

$url = "#"; 
$input = @file_get_contents($url) or die('Fehler!'); 

if(preg_match_all('~<span class="a">\s*(.*?)\s*</span>~si', $input, $item_name)); 

$image = imagecreatefrompng("bg.png"); 
imagesavealpha($image, true); 
imagealphablending($image, true); 
$finalImage = imagecreatetruecolor(800,200); 

$font = '../arial.ttf'; 
$color = imagecolorallocate($finalImage, 0, 0, 0); 
$color_time = imagecolorallocate($finalImage, 100, 100, 100); 

imagettftext($image, 10, 0, 23, 15, $color, $font, $item_name[1][0]); 
imagettftext($image, 10, 0, 22, 33, $color, $font, $item_name[1][1]); 
imagettftext($image, 10, 0, 22, 51, $color, $font, $item_name[1][2]); 
imagettftext($image, 10, 0, 22, 69, $color, $font, $item_name[1][3]); 
imagettftext($image, 10, 0, 22, 87, $color, $font, $item_name[1][4]); 
imagettftext($image, 10, 0, 22, 105, $color, $font, $item_name[1][5]); 
imagettftext($image, 10, 0, 22, 123, $color, $font, $item_name[1][6]); 
imagettftext($image, 10, 0, 22, 141, $color, $font, $item_name[1][7]); 
imagettftext($image, 10, 0, 22, 159, $color, $font, $item_name[1][8]); 
imagettftext($image, 10, 0, 22, 177, $color, $font, $item_name[1][9]); 
imagettftext($image, 10, 0, 22, 195, $color, $font, $item_name[1][10]); 

header('Content-type: image/png'); 
imagepng($image); 

Вы знаете, как? Потому что я не понимаю. Я уже много гугл. Вы, ребята, должны знать, что я не очень добрался до PHP, вот почему мне нужна помощь. Если у вас есть вопросы, пожалуйста, спросите!

+0

gd только размещает текст, в котором вы его указываете. он не имеет «выравнивание влево» или «выравнивание вправо». вам нужно реализовать это самостоятельно: http://php.net/manual/en/function.imagettfbbox.php –

+0

@MarcB ok, и как? – ZarneXxX

+0

прочитайте ссылку. научитесь использовать предоставленные вами инструменты. выйти из менталитета «найти функцию' do_exactly_what_I_need() ') и войти в мышление' use(); simple_tools(); предоставлена(); to_accomplish(); complex_things(); ' –

ответ

1

Очень ОЧИСТИТЬ версия FUNC, с примерами ....

<?php 

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) { 
    /************ 
    simple function that calculates the *exact* bounding box (single pixel precision). 
    The function returns an associative array with these keys: 
    left, top: coordinates you will pass to imagettftext 
    width, height: dimension of the image you have to create 
    *************/ 
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text); 
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7])); 
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7])); 

    return array( 
     "left" => abs($minX) - 1, 
     "top" => abs($minY) - 1, 
     "width" => $maxX - $minX, 
     "height" => $maxY - $minY, 
     "box" => $rect 
    ); 
} 

// Example usage - gif image output 

$text_string = "Hullo World"; 
$font_ttf  = "./fonts/arial.ttf"; 
$font_size  = 22; 
$text_angle  = 0; 
$text_padding = 10; // Img padding - around text 

$the_box  = calculateTextBox($text_string, $font_ttf, $font_size,  $text_angle); 

$imgWidth = $the_box["width"] + $text_padding; 
$imgHeight = $the_box["height"] + $text_padding; 

$image = imagecreate($imgWidth,$imgHeight); 
imagefill($image, imagecolorallocate($image,200,200,200)); 

$color = imagecolorallocate($image,0,0,0); 
imagettftext($image, 
    $font_size, 
    $text_angle, 
    $the_box["left"] + ($imgWidth/2) - ($the_box["width"]/2), 
    $the_box["top"] + ($imgHeight/2) - ($the_box["height"]/2), 
    $color, 
    $font_ttf, 
    $text_string); 

    header("Content-Type: image/gif"); 
    imagegif($image); 
    imagedestroy($image); 

?> 

[помните:., До или после тега, без пробелов, из-за заголовка() вызов, вы Жаркое! ]

Если вы ищете удобное выравнивание текста, вам нужно использовать команду imagettfbbox(). При заданных правильных параметрах он вернет границы вашего текстового поля в массив, что позволит вам вычислить координаты x и y, которые необходимо использовать для центрирования или выравнивания текста.

Горизонтальный пример центрирования:

<?php 
    $tb = imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!'); 
?> 

$ Т.Б. будет содержать:

Array 
(
    [0] => 0 // lower left X coordinate 
    [1] => -1 // lower left Y coordinate 
    [2] => 198 // lower right X coordinate 
    [3] => -1 // lower right Y coordinate 
    [4] => 198 // upper right X coordinate 
    [5] => -20 // upper right Y coordinate 
    [6] => 0 // upper left X coordinate 
    [7] => -20 // upper left Y coordinate 
) 

Для горизонтального выравнивания, необходимо вычесть "текстовое поле в" ширина {$ Тб [2] или $ tb [4]} из ширины изображения, а затем вычесть на два.

говорят у вас есть 200px широкий образ, вы могли бы сделать что-то вроде этого:

<?php 

    $x = ceil((200 - $tb[2])/2); // lower left X coordinate for text 
    imagettftext($im, 17, 0, $x, $y, $tc, '../arial.ttf', 'Hello world!'); // write text to image 
?> 

Это даст вам идеальное центрирование по горизонтали для текста, дать или взять 1 пиксель. Повеселись!

http://php.net/manual/en/function.imagettfbbox.php