使用GD和PHP居中对齐多行文本 [英] Center aligning multiple lines of text with GD and PHP

查看:89
本文介绍了使用GD和PHP居中对齐多行文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在图像上打印多行文本并将它们居中对齐.

I'm trying to print multiple lines of text on an image and center align them.

   这是
一串文本

    This is
A string of text

现在,我只剩下整个字符串的左位置.有什么捷径可以使它起作用吗?我认为可能必须是整个字符串上有一个getttfbox,然后在换行符上爆炸,然后将新文本放在较大的ttfbox中.这真是个痛苦的事...

Right now, I only have the left position for the whole string. Any shortcuts on getting that to work? I think it might have to be a getttfbox on the whole string, then an explode on the line breaks, then center the new text inside that larger ttfbox. That's a pain in the ass...

提出解决方案:

    foreach ( $strings as $index => $string ) {
        $parts = explode ( "\n", $string['string'] );
        if ( count ( $parts ) > 1 ) {
            $bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $string['string'] );
            $width = $bounds[2] - $bounds[0];
            $height = $bounds[3] - $bounds[5];
            $line_height = $height / count ( $parts );

            foreach ( $parts as $index => $part ) {
                $bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $part );
                $new_width = $bounds[2] - $bounds[0];
                $diff = ( $width - $new_width ) / 2;
                $new_left = $string['left'] + $diff;

                $new_string = $string;
                $new_string['left'] = $new_left;
                $new_string['top'] = $string['top'] + ($index * $line_height);
                $new_string['string'] = $part;
                $new_strings[] = $new_string;
            }
        }
    }

    if ( $new_strings )
        $strings = $new_strings;

在这种情况下,每个$ string是一个数组,其中包含有关如何打印和打印什么的信息.希望能对某人有所帮助.

In this case, each $string is an array with some information about how and what to print. Hope that helps someone.

推荐答案

您可以使用 stil/gd-text类.免责声明:我是作者.

You can use stil/gd-text class. Disclaimer: I am the author.

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

$img = imagecreatefromjpeg('image.jpg');

$textbox = new Box($img);
$textbox->setFontSize(12);
$textbox->setFontFace('arial.ttf');
$textbox->setFontColor(new Color(0, 0, 0));
$textbox->setBox(
    50,  // distance from left edge
    50,  // distance from top edge
    200, // textbox width
    100  // textbox height
);

// now we have to align the text horizontally and vertically inside the textbox
$textbox->setTextAlign('center', 'top');
// it accepts multiline text
$textbox->draw("This is\na string of text");

演示:

这篇关于使用GD和PHP居中对齐多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆