【发布时间】:2015-03-14 15:29:29
【问题描述】:
我正在使用 GD lib 在图像上叠加文本。我想在边界框中包装一个字符串并尽可能地适合文本。
这是我目前所得到的:
//dimension of the image I'm placing the text on
$img_w = imagesx($this->img);
$img_h = imagesy($this->img);
//Get the dimensions of the text bounding box
$bbox = imagettfbbox($size, 0, $font, $text);
$w = (abs($bbox[2])+(abs($bbox[0])));
$h = (abs($bbox[5])+(abs($bbox[3])));
接下来我需要做一些检查。如果$w > $img_w 那么我想在字符串中间添加一个换行符。然后再次检查$w > $img_w。如果它仍然太大,则分成三等份,依此类推,直到它适合图像宽度。
我还需要在每次添加换行符时检查 $h > $img_h。如果这是真的,那么我已经没有空间来适应这个尺寸的图像中的文本了。所以我需要开始减小文本大小,直到合适为止。
您可以在这里看到与我想要实现的相同的东西:http://memegenerator.net/Instagram
我有一个递归方法来检索文本大小,因此当我重叠它时我可以将它放在图像上:
private function get_text_size($size, $font, $text){
//dimension of the image I'm placing the text on
$img_w = imagesx($this->img);
$img_h = imagesy($this->img);
//Get the dimensions of the text bounding box
$bbox = imagettfbbox($size, 0, $font, $text);
//add some space around the text too
$w = (abs($bbox[2])+(abs($bbox[0]));
$h = (abs($bbox[5])+(abs($bbox[3]));
if( $w > $img_w ){
//split string in half
$tmp = explode(' ', $text);
$word_count = (count($tmp)/2);
$tmp[$word_count] .= "\n";
//rebuild the string with the line break(s) and check the size again.
$text = '';
foreach($tmp as $word){
$text .= $word.' ';
}
return $this->get_text_size($size, $font, $text);
}
return array($size, $w, $h);
}
这只会让我陷入无限循环,就像换行符不起作用一样。我检查过类似的问题(How do I add a line break at the mid point of a string split by whitespace、Wrap lines of text within image boundaries using gd),但没有一个能真正解决这个问题。
我有点期望会有一个简单的函数来做到这一点,但我找不到一个,也想不出最好的方法。
【问题讨论】:
标签: php image-processing gd word-wrap imagettftext