imagettftext():计算字体大小以确保文本适合图像宽度 [英] imagettftext(): calculate font size to ensure text fits image width

查看:819
本文介绍了imagettftext():计算字体大小以确保文本适合图像宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用imagettftext()在图像上写动态文本,并且希望它适合我的图像宽度.

I'm using imagettftext() to write dynamic text on an image and I want it to fit my image width.

如何通过文本长度计算字体大小?

How can I calculate the font size by the text lenght?

推荐答案

您可以在使用imagettfbbox函数输出TTF文本之前计算出TTF文本的边界框.不幸的是,没有直接缩放方法来适合宽度,因此您必须自己动手.

You can calculate the bounding box of TTF text before outputting it with the imagettfbbox function. Unfortunately there is no direct way of scaling to fit a width, so you'll have to do it yourself.

一种实现方法是将默认字体大小为20的文本传递给imagettfbbox并从中获取宽度.然后,您可以通过计算比例因子来计算文本的大小,以适合您想要的大小:

One way of doing it is to pass the text with a default font size of, say 20, to imagettfbbox and retrieve the width from it. You can then calculate how much smaller or bigger the text should be to fit the size you want by calculating a scale factor:

scale = targetWidth / bboxWidth;

然后以适当的大小绘制文本:

Then draw the text with the proper size:

fontSize = 20 * scale;

使用imagettftext功能.字体不能以这种方式完美地缩放100%,但是您会得到很好的近似值.

using the imagettftext function. Fonts don't scale 100% perfectly this way, but you'll get a very good approximation.

请参见imagettfbox 此处的文档.

这篇关于imagettftext():计算字体大小以确保文本适合图像宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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