PHP:imagettftext& imagettfbbox - 单词的碰撞检测

时间:2013-11-04 23:38:38

标签: php collision-detection true-type-fonts

我有一个数组中的单词列表,我可以使用imagettftext写入PNG。

imagettfbbox用于确定下一个单词的去向。

我想检查我试图写入图像的当前单词是否与之前写入的单词重叠(我假设imagettfbbox是要走的路?)

以下是我认为代码看起来的样子(我无法理解如何做到这一点!):

If the current word will overlap with previous word
  Position current word further down an ever increasing spiral until it doesn't collide

目前我的代码会将所有单词写入图像而不重叠但没有任何角度(这是我希望将来处理的内容 - 没有单词冲突)

$handle = ImageCreate(1000, 500) or die ("Cannot Create image");

//Background Colour
$bg_color = ImageColorAllocate($handle, 0, 150, 255); 
$txt_color = ImageColorAllocate($handle, 0, 0, 0);

// First we create our bounding box for the first text
$bbox = imagettfbbox($fontsize, $angle, $font, $word);

// Set X Coord
$x = ($bbox[2] - $bbox[0]);

// Set Y Coord
$y += ($bbox[7] - $bbox[1]);

// Write word to image
ImageTTFText($image, $fontsize, $angle, $x, $y, $txt_color, $font, $word);

此刻您可以看到的代码非常静态,并且也不会将单词限制在图像的大小(也是我想要的)。

任何帮助都会非常感激,过去两周我一直坚持这一点,并且真的想继续前进!

2 个答案:

答案 0 :(得分:0)

我很久没有这样做了,但很久以前我曾经写过一个图像处理课。这是我的函数的片段,它执行类似的任务。我的整个函数实际上考虑了垂直,居中,左/右对齐,粗体,TTF /非TTF和自动换行(以及这些的任何逻辑组合)。如果你需要自动换行,你必须对字符串进行计算,然后在弄乱边界框之前将其分解为一个行数组。

这段代码位于一个foreach循环中,它迭代了破碎的字符串。这是像你一样进行盒子计算的部分。它看起来很相似,但我的算法有点不同。

// Calculate Deviation
$dx = ($box[2] - $box[0]) / 2 - ($box[2] - $box[4]) / 2; // Left-Right
$dy = ($box[3] - $box[1]) / 2 + ($box[7] - $box[1]) / 2; // Top-Bottom

// Some calculations for alignments were here

// Draw the text
$success = imagettftext($this->image, $this->settings['font'], (int)$angle, $x, $y, $color, $font_file, $string);

如果您对我所描述的其余部分感兴趣,我可以提供全部功能。它利用位掩码进行标记。我不记得它是否处理角度太过诚实,但我认为它主要是这样做的。

希望这有帮助。

答案 1 :(得分:0)

我花了一段时间,但我想出来了......

我就这样做了:

其中$ i是要写入图像的单词的编号。

do{
    $startx += ($i / 2 * cos($i));
    $starty += ($i / 2 * sin($i));
}while(intersection($boundingbox, $startx, $starty, $previouscoordinates, $i));

intersects方法获取要写入的当前单词,其边界框坐标,start(x,y)以及已写入图像的先前单词的所有坐标。该方法检查当前要写入的单词是否与此开始(x,y)点的任何前一个单词相交。