PHP imagettftext基线解决方法 [英] PHP imagettftext baseline workaround

查看:261
本文介绍了PHP imagettftext基线解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写使用PHP将文本打印到图像上.但是,功能imagettftext()使用基线,而我需要文本垂直居中.

I am writing to print text to an image using PHP. However, the function imagettftext() uses the baseline, whereas I need the text vertically centered.

所以,我要么需要一种打印文本y的方法,而不是从顶部到基线的距离,而是从边界框的顶部到顶部的打印距离,或者我需要一种可以确定边界框的顶部与基线之间的距离的方法

So, I either need a method to print text with y not the distance from top to baseline, but from top to top of bounding box OR I need a method using which I could determine the distance between top of bounding box and baseline.

显然,我让您感到困惑.因此,要明确地说:我知道函数imagettfbbox().使用该功能,我可以确定结果文本框的高度和宽度.但是,当使用imagettftext()进行打印时,其高度对于垂直对齐完全没有用,因为Y参数不是到框顶部(甚至底部)的距离,但至少不是我可以使用的具有高度的距离.但距文本基线的距离.

Apparently, I am confusing you. So, to make it clear: I am aware of the function imagettfbbox(). Using that function I can determine height and width of resulting text box. Its height, however, is utterly useless for vertical alignment when printing with imagettftext(), because the Y parameter is not the distance to the top of the box (or even the bottom, but at least something I could have used having the height) but the distance to the baseline of the text within.

为什么我不接受最新答案?

Why am I not accepting the latest answer?

在答案下方查看我的最新评论,并将此图像用作参考.

See my latest comment below the answer, and use this image as a reference.

推荐答案

我不知道答案是否仍然有意义.但是,imagettfbbox()函数不仅为边框的高度和宽度提供了更多信息.它的设计正是为了返回imagettftext()所需的信息,以便根据需要管理文本.

I do not know if the answer still interested.However, the imagettfbbox() function give you more information than simply the height and the width of the bounding box. It's designed exactly to return information needed by the imagettftext() to manage the text as you want.

诀窍在于,从imagettfbbox()返回的坐标与绝对左上角无关,而与特定文本的字体基线有关.这是因为框是在点坐标中指定的,而这些通常是负数.

The trick lies in the fact that the coordinates returned from imagettfbbox() are not related to the absolute top left corner, but to the baseline of the font for the particular text. This is the reason because the box is specified in point coordinates, and these are often negative.

简而言之:

$dims = imagettfbbox($fontsize, 0, $font, $text);

$ascent = abs($dims[7]);
$descent = abs($dims[1]);
$width = abs($dims[0])+abs($dims[2]);
$height = $ascent+$descent;

...

// In the example code, for the vertical centering of the text, consider
// the simple following formula

$y = (($imageHeight/2) - ($height/2)) + $ascent;

这非常适合我的项目. 希望有帮助.

This works perfectly for my projects. Hope this help.

对不起,英语. 马可.

Sorry for english. Marco.

这篇关于PHP imagettftext基线解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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