imagettftext(): calculate font size to ensure text fits image width

扶醉桌前 提交于 2019-12-17 19:54:21

问题


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?


回答1:


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.

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;

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

See the documentation of imagettfbox here.




回答2:


while (itsTooBigAccordingToimagettftext() && $fontSize > 0) {
    $fontSize--;
}


来源:https://stackoverflow.com/questions/10689225/imagettftext-calculate-font-size-to-ensure-text-fits-image-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!