Get the calculated cell width for a given value.

@param string $fontName
@param int    $fontSize
@param mixed  $value

@return float|int
324890
public function getCellWidth($fontName, $fontSize, $value)
    {
        $width = 1;
        foreach ($this->getSingleCharacterArray($value) as $char) {
            $width += $this->getCharacterWidth($fontName, $fontSize, $char);
        }

        return $width;
    }
738171
def com_google_fonts_check_xavgcharwidth(ttFont):
  """"""
  current_value = ttFont['OS/2'].xAvgCharWidth
  ACCEPTABLE_ERROR = 10  # Width deviation tolerance in font units

  # Since version 3, the average is computed using _all_ glyphs in a font.
  if ttFont['OS/2'].version >= 3:
    calculation_rule = "the average of the widths of all glyphs in the font"
    if not ttFont['hmtx'].metrics:  # May contain just '.notdef', which is valid.
      yield FAIL, Message("missing-glyphs",
                          "CRITICAL: Found no glyph width data in the hmtx table!")
      return

    width_sum = 0
    count = 0
    for glyph_id in ttFont['glyf'].glyphs:  # At least .notdef must be present.
      width = ttFont['hmtx'].metrics[glyph_id][0]
      # The OpenType spec doesn't exclude negative widths, but only positive
      # widths seems to be the assumption in the wild?
      if width > 0:
        count += 1
        width_sum += width

    expected_value = int(round(width_sum / count))
  else:  # Version 2 and below only consider lowercase latin glyphs and space.
    calculation_rule = ("the weighted average of the widths of the latin"
                        " lowercase glyphs in the font")
    weightFactors = {
        'a': 64,
        'b': 14,
        'c': 27,
        'd': 35,
        'e': 100,
        'f': 20,
        'g': 14,
        'h': 42,
        'i': 63,
        'j': 3,
        'k': 6,
        'l': 35,
        'm': 20,
        'n': 56,
        'o': 56,
        'p': 17,
        'q': 4,
        'r': 49,
        's': 56,
        't': 71,
        'u': 31,
        'v': 10,
        'w': 18,
        'x': 3,
        'y': 18,
        'z': 2,
        'space': 166
    }
    glyph_order = ttFont.getGlyphOrder()
    if not all(character in glyph_order for character in weightFactors):
      yield FAIL, Message("missing-glyphs",
                          "Font is missing the required latin lowercase "
                          "letters and/or space.")
      return

    width_sum = 0
    for glyph_id in weightFactors:
      width = ttFont['hmtx'].metrics[glyph_id][0]
      width_sum += (width * weightFactors[glyph_id])

    expected_value = int(width_sum / 1000.0 + 0.5)  # round to closest int

  difference = abs(current_value - expected_value)

  # We accept matches and off-by-ones due to rounding as correct.
  if current_value == expected_value or difference == 1:
    yield PASS, "OS/2 xAvgCharWidth value is correct."
  elif difference < ACCEPTABLE_ERROR:
    yield INFO, (f"OS/2 xAvgCharWidth is {current_value} but it should be"
                 f" {expected_value} which corresponds to {calculation_rule}."
                  " These are similar values, which"
                  " may be a symptom of the slightly different"
                  " calculation of the xAvgCharWidth value in"
                  " font editors. There's further discussion on"
                  " this at https://github.com/googlefonts/fontbakery"
                  "/issues/1622")
  else:
    yield WARN, (f"OS/2 xAvgCharWidth is {current_value} but it should be"
                 f" {expected_value} which corresponds to {calculation_rule}.")
44517
def text_width(string, font_name, font_size):
    """"""
    return stringWidth(string, fontName=font_name, fontSize=font_size)
1371948
function getTextWidth( $size, $text )
    {
        // this function should not change any of the settings, though it will need to
        // track any directives which change during calculation, so copy them at the start
        // and put them back at the end.
        $this->pushTextState( $this->currentTextState );

        if (!$this->numFonts)
        {
            $this->selectFont('./fonts/Helvetica');
        }

        // converts a number or a float to a string so it can get the width
        $text = "$text";
        // hmm, this is where it all starts to get tricky - use the font information to
        // calculate the width of each character, add them up and convert to user units
        $w = 0;
        $len = strlen( $text );
        $cf = $this->currentFont;
        for ( $i = 0; $i < $len; $i++ )
        {
            $f = 1;
            $directiveArray = $this->PRVTcheckTextDirective( $text, $i, $f );
            $directive = $directiveArray['directive'];
            if ( $directive )
            {
                if ($f)
                {
                    $this->setCurrentFont();
                    $cf = $this->currentFont;
                }
                $i = $i + $directive-1;
            }
            else
            {
                $char = ord( $text[$i] );
                if ( isset($this->fonts[$cf]['differences'][$char] ) )
                {
                    // then this character is being replaced by another
                    $name = $this->fonts[$cf]['differences'][$char];
                    if ( isset($this->fonts[$cf]['C'][$name]['WX'] ) )
                    {
                        $w += $this->fonts[$cf]['C'][$name]['WX'];
                    }
                }
                else if ( isset($this->fonts[$cf]['C'][$char]['WX'] ) )
                {
                    $w += $this->fonts[$cf]['C'][$char]['WX'];
                }
                else
                {
                    $w += 700;
                }
            }
        }

        $this->popTextState();
        $this->setCurrentFont();

        return $w*$size/1000;
    }
822500
function hasFontLoaded (window, fontName) {
    var testSize = 16
    if (!fontTestElement) {
        fontTestElement = window.document.createElement('canvas')
        fontTestElement.width = testSize
        fontTestElement.height = testSize
        fontTestElement.style.display = 'none'

        ctx = fontTestElement.getContext('2d')
        window.document.body.appendChild(fontTestElement)
    }

    fontTestElement.width = testSize
    ctx.fillStyle = 'rgba(0, 0, 0, 0)'
    ctx.fillRect(0, 0, testSize, testSize)
    ctx.font = testSize + "px __cc2d_" + fontName
    ctx.fillStyle = 'rgba(255, 255, 255, 1)'
    ctx.fillText("M", 0, testSize);

    var pixels = ctx.getImageData(0, 0, testSize, testSize).data

    for (var i = 0; i < testSize * testSize; i++) {
        if (pixels[i * 4] != 0) {
            fontTestElement.parentNode.removeChild(fontTestElement)
            fontTestElement = null
            return true
        }
    }

    return false
}
15717
function get_font_size()
    {

        if ($this->__font_size_calculated) {
            return $this->_props["font_size"];
        }

        if (!isset($this->_props["font_size"])) {
            $fs = self::$_defaults["font_size"];
        } else {
            $fs = $this->_props["font_size"];
        }

        if (!isset($this->_parent_font_size)) {
            $this->_parent_font_size = self::$default_font_size;
        }

        switch ((string)$fs) {
            case "xx-small":
            case "x-small":
            case "small":
            case "medium":
            case "large":
            case "x-large":
            case "xx-large":
                $fs = self::$default_font_size * self::$font_size_keywords[$fs];
                break;

            case "smaller":
                $fs = 8 / 9 * $this->_parent_font_size;
                break;

            case "larger":
                $fs = 6 / 5 * $this->_parent_font_size;
                break;

            default:
                break;
        }

        // Ensure relative sizes resolve to something
        if (($i = mb_strpos($fs, "em")) !== false) {
            $fs = (float)mb_substr($fs, 0, $i) * $this->_parent_font_size;
        } else if (($i = mb_strpos($fs, "ex")) !== false) {
            $fs = (float)mb_substr($fs, 0, $i) * $this->_parent_font_size;
        } else {
            $fs = (float)$this->length_in_pt($fs);
        }

        //see __set and __get, on all assignments clear cache!
        $this->_prop_cache["font_size"] = null;
        $this->_props["font_size"] = $fs;
        $this->__font_size_calculated = true;
        return $this->_props["font_size"];

    }
283539
function textSize(width, height, fontSize, scale) {
	    var stageWidth = parseInt(width, 10);
	    var stageHeight = parseInt(height, 10);

	    var bigSide = Math.max(stageWidth, stageHeight);
	    var smallSide = Math.min(stageWidth, stageHeight);

	    var newHeight = 0.8 * Math.min(smallSide, bigSide * scale);
	    return Math.round(Math.max(fontSize, newHeight));
	}
353667
@Override protected void resizeDynamicText() {
        double maxWidth = unitText.isVisible() ? width - size * 0.275 : width - size * 0.1;
        double fontSize = 0.24 * size;
        valueText.setFont(Fonts.latoRegular(fontSize));
        if (valueText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(valueText, maxWidth, fontSize); }

        maxWidth = width - size * 0.55;
        fontSize = size * 0.18;
        deviationText.setFont(Fonts.latoRegular(fontSize));
        if (deviationText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(deviationText, maxWidth, fontSize); }

        maxWidth = width - size * 0.9;
        fontSize = size * 0.12;
        deviationUnitText.setFont(Fonts.latoRegular(fontSize));
        if (deviationUnitText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(deviationUnitText, maxWidth, fontSize); }
    }
596188
public float getWidthPointKerned(String text, float fontSize) {
        float size = getWidth(text) * 0.001f * fontSize;
        if (!hasKernPairs())
            return size;
        int len = text.length() - 1;
        int kern = 0;
        char c[] = text.toCharArray();
        for (int k = 0; k < len; ++k) {
            kern += getKerning(c[k], c[k + 1]);
        }
        return size + kern * 0.001f * fontSize;
    }
886693
public function getTextBox($X, $Y, $FontName, $FontSize, $Angle, $Text)
    {
        $coords = imagettfbbox($FontSize, 0, $this->loadFont($FontName, 'fonts'), $Text);

        $a = deg2rad($Angle);
        $ca = cos($a);
        $sa = sin($a);
        $RealPos = [];
        for ($i = 0; $i < 7; $i += 2) {
            $RealPos[$i / 2]["X"] = $X + round($coords[$i] * $ca + $coords[$i + 1] * $sa);
            $RealPos[$i / 2]["Y"] = $Y + round($coords[$i + 1] * $ca - $coords[$i] * $sa);
        }

        $RealPos[TEXT_ALIGN_BOTTOMLEFT]["X"] = $RealPos[0]["X"];
        $RealPos[TEXT_ALIGN_BOTTOMLEFT]["Y"] = $RealPos[0]["Y"];
        $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["X"] = $RealPos[1]["X"];
        $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["Y"] = $RealPos[1]["Y"];
        $RealPos[TEXT_ALIGN_TOPLEFT]["X"] = $RealPos[3]["X"];
        $RealPos[TEXT_ALIGN_TOPLEFT]["Y"] = $RealPos[3]["Y"];
        $RealPos[TEXT_ALIGN_TOPRIGHT]["X"] = $RealPos[2]["X"];
        $RealPos[TEXT_ALIGN_TOPRIGHT]["Y"] = $RealPos[2]["Y"];
        $RealPos[TEXT_ALIGN_BOTTOMMIDDLE]["X"] = ($RealPos[1]["X"] - $RealPos[0]["X"]) / 2 + $RealPos[0]["X"];
        $RealPos[TEXT_ALIGN_BOTTOMMIDDLE]["Y"] = ($RealPos[0]["Y"] - $RealPos[1]["Y"]) / 2 + $RealPos[1]["Y"];
        $RealPos[TEXT_ALIGN_TOPMIDDLE]["X"] = ($RealPos[2]["X"] - $RealPos[3]["X"]) / 2 + $RealPos[3]["X"];
        $RealPos[TEXT_ALIGN_TOPMIDDLE]["Y"] = ($RealPos[3]["Y"] - $RealPos[2]["Y"]) / 2 + $RealPos[2]["Y"];
        $RealPos[TEXT_ALIGN_MIDDLELEFT]["X"] = ($RealPos[0]["X"] - $RealPos[3]["X"]) / 2 + $RealPos[3]["X"];
        $RealPos[TEXT_ALIGN_MIDDLELEFT]["Y"] = ($RealPos[0]["Y"] - $RealPos[3]["Y"]) / 2 + $RealPos[3]["Y"];
        $RealPos[TEXT_ALIGN_MIDDLERIGHT]["X"] = ($RealPos[1]["X"] - $RealPos[2]["X"]) / 2 + $RealPos[2]["X"];
        $RealPos[TEXT_ALIGN_MIDDLERIGHT]["Y"] = ($RealPos[1]["Y"] - $RealPos[2]["Y"]) / 2 + $RealPos[2]["Y"];
        $RealPos[TEXT_ALIGN_MIDDLEMIDDLE]["X"] = ($RealPos[1]["X"] - $RealPos[3]["X"]) / 2 + $RealPos[3]["X"];
        $RealPos[TEXT_ALIGN_MIDDLEMIDDLE]["Y"] = ($RealPos[0]["Y"] - $RealPos[2]["Y"]) / 2 + $RealPos[2]["Y"];

        return $RealPos;
    }
87904
public static function getTextWidthPixelsApprox($columnText, PHPExcel_Style_Font $font = null, $rotation = 0)
    {
        $fontName = $font->getName();
        $fontSize = $font->getSize();

        // Calculate column width in pixels. We assume fixed glyph width. Result varies with font name and size.
        switch ($fontName) {
            case 'Calibri':
                // value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font.
                $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText));
                $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size
                break;

            case 'Arial':
                // value 7 was found via interpolation by inspecting real Excel files with Arial 10 font.
//                $columnWidth = (int) (7 * PHPExcel_Shared_String::CountCharacters($columnText));
                // value 8 was set because of experience in different exports at Arial 10 font.
                $columnWidth = (int) (8 * PHPExcel_Shared_String::CountCharacters($columnText));
                $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size
                break;

            case 'Verdana':
                // value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font.
                $columnWidth = (int) (8 * PHPExcel_Shared_String::CountCharacters($columnText));
                $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size
                break;

            default:
                // just assume Calibri
                $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText));
                $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size
                break;
        }

        // Calculate approximate rotated column width
        if ($rotation !== 0) {
            if ($rotation == -165) {
                // stacked text
                $columnWidth = 4; // approximation
            } else {
                // rotated text
                $columnWidth = $columnWidth * cos(deg2rad($rotation))
                                + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation
            }
        }

        // pixel width is an integer
        return (int) $columnWidth;
    }
943996
public static Font getFont (int style, Size size) {
		return getFont(getDefaultFont(), size).deriveFont(style);
	}
1353731
def calculate_width(font_size, text)
      return 0 if text.nil?
      @d.pointsize = font_size
      @d.font = @font if @font
      @d.get_type_metrics(@base_image, text.to_s).width
    end
930012
def font_width(self):
        """"""
        return self.get_font_width(font_name=self.font_name, font_size=self.font_size)
1329548
public function getLegendSize(array $Format = [])
    {
        $FontName = isset($Format["FontName"]) ? $this->loadFont($Format["FontName"], 'fonts') : $this->FontName;
        $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
        $Margin = isset($Format["Margin"]) ? $Format["Margin"] : 5;
        $Mode = isset($Format["Mode"]) ? $Format["Mode"] : LEGEND_VERTICAL;
        $BoxWidth = isset($Format["BoxWidth"]) ? $Format["BoxWidth"] : 5;
        $BoxHeight = isset($Format["BoxHeight"]) ? $Format["BoxHeight"] : 5;
        $IconAreaWidth = isset($Format["IconAreaWidth"]) ? $Format["IconAreaWidth"] : $BoxWidth;
        $IconAreaHeight = isset($Format["IconAreaHeight"]) ? $Format["IconAreaHeight"] : $BoxHeight;
        $XSpacing = isset($Format["XSpacing"]) ? $Format["XSpacing"] : 5;

        $Data = $this->DataSet->getData();

        foreach ($Data["Series"] as $SerieName => $Serie) {
            if ($Serie["isDrawable"] == true
                && $SerieName != $Data["Abscissa"]
                && isset($Serie["Picture"])
            ) {
                list($PicWidth, $PicHeight) = $this->getPicInfo($Serie["Picture"]);
                if ($IconAreaWidth < $PicWidth) {
                    $IconAreaWidth = $PicWidth;
                }
                if ($IconAreaHeight < $PicHeight) {
                    $IconAreaHeight = $PicHeight;
                }
            }
        }

        $YStep = max($this->FontSize, $IconAreaHeight) + 5;
        $XStep = $IconAreaWidth + 5;
        $XStep = $XSpacing;

        $X = 100;
        $Y = 100;

        $Boundaries = [];
        $Boundaries["L"] = $X;
        $Boundaries["T"] = $Y;
        $Boundaries["R"] = 0;
        $Boundaries["B"] = 0;
        $vY = $Y;
        $vX = $X;
        foreach ($Data["Series"] as $SerieName => $Serie) {
            if ($Serie["isDrawable"] == true && $SerieName != $Data["Abscissa"]) {
                if ($Mode == LEGEND_VERTICAL) {
                    $BoxArray = $this->getTextBox(
                        $vX + $IconAreaWidth + 4,
                        $vY + $IconAreaHeight / 2,
                        $FontName,
                        $FontSize,
                        0,
                        $Serie["Description"]
                    );

                    if ($Boundaries["T"] > $BoxArray[2]["Y"] + $IconAreaHeight / 2) {
                        $Boundaries["T"] = $BoxArray[2]["Y"] + $IconAreaHeight / 2;
                    }
                    if ($Boundaries["R"] < $BoxArray[1]["X"] + 2) {
                        $Boundaries["R"] = $BoxArray[1]["X"] + 2;
                    }
                    if ($Boundaries["B"] < $BoxArray[1]["Y"] + 2 + $IconAreaHeight / 2) {
                        $Boundaries["B"] = $BoxArray[1]["Y"] + 2 + $IconAreaHeight / 2;
                    }

                    $Lines = preg_split("/\n/", $Serie["Description"]);
                    $vY = $vY + max($this->FontSize * count($Lines), $IconAreaHeight) + 5;
                } elseif ($Mode == LEGEND_HORIZONTAL) {
                    $Lines = preg_split("/\n/", $Serie["Description"]);
                    $Width = [];
                    foreach ($Lines as $Key => $Value) {
                        $BoxArray = $this->getTextBox(
                            $vX + $IconAreaWidth + 6,
                            $Y + $IconAreaHeight / 2 + (($this->FontSize + 3) * $Key),
                            $FontName,
                            $FontSize,
                            0,
                            $Value
                        );

                        if ($Boundaries["T"] > $BoxArray[2]["Y"] + $IconAreaHeight / 2) {
                            $Boundaries["T"] = $BoxArray[2]["Y"] + $IconAreaHeight / 2;
                        }
                        if ($Boundaries["R"] < $BoxArray[1]["X"] + 2) {
                            $Boundaries["R"] = $BoxArray[1]["X"] + 2;
                        }
                        if ($Boundaries["B"] < $BoxArray[1]["Y"] + 2 + $IconAreaHeight / 2) {
                            $Boundaries["B"] = $BoxArray[1]["Y"] + 2 + $IconAreaHeight / 2;
                        }

                        $Width[] = $BoxArray[1]["X"];
                    }

                    $vX = max($Width) + $XStep;
                }
            }
        }
        $vY = $vY - $YStep;
        $vX = $vX - $XStep;

        $TopOffset = $Y - $Boundaries["T"];
        if ($Boundaries["B"] - ($vY + $IconAreaHeight) < $TopOffset) {
            $Boundaries["B"] = $vY + $IconAreaHeight + $TopOffset;
        }

        $Width = ($Boundaries["R"] + $Margin) - ($Boundaries["L"] - $Margin);
        $Height = ($Boundaries["B"] + $Margin) - ($Boundaries["T"] - $Margin);

        return ["Width" => $Width, "Height" => $Height];
    }
1070382
private function getNameTableOffset($fontHandle)
    {
        $numberOfTables = $this->unpack(substr(fread($fontHandle, 12), 4, 2));

        for ($t = 0; $t < $numberOfTables; $t++) {
            $tableDirectory = fread($fontHandle, 16);
            $szTag = substr($tableDirectory, 0, 4);
            if (strtolower($szTag) == 'name') {
                return $this->unpack(substr($tableDirectory, 8, 4), 'N');
            }
        }

        fclose($fontHandle);
        throw new \Exception('Can\'t find name table in ' . $this->fileName);
    }
464284
private function calculateCellSize()
    {
        $this->_font = ZfPdf\Font::fontWithName(ZfPdf\Font::FONT_HELVETICA);
        $i = 0;
        $larg = Array();

        foreach ($this->_arrayForm['gridfieldsconfig'] as $field => $value) {
            if ($field == 'dta_cadastro' or $field == 'dta_atualizacao') {
                $larg[$i] = 4;
            } elseif ($field == 'ind_status') {
                $larg[$i] = 2;
            } elseif ($value['type'] == 'primarykey') {
                $larg[$i] = 2;
            } else {
                $fieldName = $this->_arrayLocale->translate($field);
                $larg[$i] = $this->widthForStringUsingFontSize($fieldName, $this->_font, 8);
            }
            $i++;
        }
        /*
          foreach ($this->_arrayData as $value) {
          $i = 0;
          foreach ($value as $value2) {
          $value2 = strip_tags($value2);
          if ($larg[$i] < strlen($value2)) {
          $larg[$i] = strlen($value2);
          }
          $i++;
          }
          }
         */

        return $larg;
    }