如何控制使用`imagettftext()`生成的文本的文本对齐方式? [英] How to control text alignment for text generated using `imagettftext()`?

查看:770
本文介绍了如何控制使用`imagettftext()`生成的文本的文本对齐方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP GD库中的imagettftext函数,只能将左对齐的文本绘制到图像上.至少看起来如此,也许我正在丢失一些东西.

Using the imagettftext function from the PHP GD library, one can only draw text that is left-aligned onto an image. At least so it would seem, perhaps I'm missing something.

如何控制绘制在图像上的文本的对齐方式?即左/中/右(/合理-不必要,但有用)

How can I control the alignment of the text drawn onto an image? i.e. left / center / right (/ justified - not necessary, but useful)

我应该提到的是,当绘制的文本包含多行时(例如"bla bla bla/n和bla的另一行"),对齐方式是可见的.

I should mention that the alignment is visible when the drawn text contains multiple lines (e.g. "bla bla bla/nAnd another line of bla.").

推荐答案

imagettftext() 不是在某种形式的盒子"里写东西,而只是在给定的坐标下写东西.要正确显示文字,您必须计算正确的坐标,以使其看起来像是右对齐或居中.

with imagettftext() you're not writing into some kind of "box" but just at the given coordnates. to alingn the text properly, you'll have to calculate the correct coordinates to make it "look like" it's right-aligned or centered.

为此,您可以使用 imagettfbox() 来获取文本的大小-剩下的就是简单的数学运算:

to do so, you can use imagettfbox() to get the size of your text - the rest is simple math:

  • 要右对齐,请将[textarea-width]-[textwidth]添加到您的X-坐标
  • ([textarea-width]-[textwidth]) / 2居中添加到X坐标
  • to right-align add [textarea-width]-[textwidth] to your X-coordinate
  • to center add ([textarea-width]-[textwidth]) / 2 to your X-coordinate

(* textarea =您要在图像中写入文本的区域-应该知道它的大小)

这篇关于如何控制使用`imagettftext()`生成的文本的文本对齐方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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