/** * @param Text $element * * @return mixed[] [float $x, float $y, ZendAbstractFont $font] */ private function computeTextPos(Text $element, ZendAbstractFont $font) { $fontStyle = $element->getFontStyle(); $scale = $fontStyle->getSize() / (double) $font->getUnitsPerEm(); $x = $element->getX(); $y = $element->getY(); switch ($fontStyle->getHAlign()) { case FontStyle::HORIZONTAL_ALIGN_MIDDLE: $glyphNumbers = $font->glyphNumbersForCharacters(TextUtils::getCodes($element->getText())); $x -= 0.5 * $scale * array_sum($font->widthsForGlyphs($glyphNumbers)); break; case FontStyle::HORIZONTAL_ALIGN_RIGHT: $glyphNumbers = $font->glyphNumbersForCharacters(TextUtils::getCodes($element->getText())); $x -= $scale * array_sum($font->widthsForGlyphs($glyphNumbers)); break; } switch ($fontStyle->getVAlign()) { case FontStyle::VERTICAL_ALIGN_TOP: $y -= $scale * ($font->getAscent() - $font->getDescent()); break; case FontStyle::VERTICAL_ALIGN_CENTRAL: $y -= 0.5 * $scale * $font->getAscent(); break; case FontStyle::VERTICAL_ALIGN_BOTTOM: $y -= $scale * ($font->getDescent() + $font->getDescent()); break; } return [$x, $y]; }
public function widthForStringUsingFontSize($string, AbstractFont $font, $fontSize) { $drawingString = iconv('UTF-8', 'UTF-16BE//IGNORE', $string); $characters = array(); for ($i = 0; $i < strlen($drawingString); $i++) { $characters[] = ord($drawingString[$i++]) << 8 | ord($drawingString[$i]); } $glyphs = $font->glyphNumbersForCharacters($characters); $widths = $font->widthsForGlyphs($glyphs); $stringWidth = array_sum($widths) / $font->getUnitsPerEm() * $fontSize; return $stringWidth; }