KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Find text height and width with SVG
PRODUCT: 4D | VERSION: 12 | PLATFORM: Mac & Win
Published On: August 5, 2010

It is possible with 4D SVG commands to find a given selection of text's height and width. This is valuable because it can return dynamic values depending on font, style, and size of text.

The following code creates an SVG image in memory, exports it to a picture, and then uses PICTURE PROPERTIES to return the size of the given text:

C_PICTURE(mypic)
C_TEXT(root;ref)
C_LONGINT(width;height)
root:=DOM Create XML Ref("svg";"https://www.w3.org/2000/svg")
ref:=DOM Create XML element(root;"text";\   //create text
  "font-family";"Arial";\   //set font
  "font-size";"11";\   //set size
  "font-weight";"bold";\    //set style
  "y";"1em")   //set Y coordinate
DOM SET XML ELEMENT VALUE(ref;"Sample Text")
SVG EXPORT TO PICTURE(root;mypic;Get XML Data Source)
DOM CLOSE XML(root)
PICTURE PROPERTIES(mypic;width;height)


The text (in this case "Sample Text") height and width are returned into the width and height parameters.

One important note is that in the SVG coordinate system, 0,0 is the upper left corner of an image. In a font's system though the y coordinate 0 is the base of a capital letter. See the graphic below showing the 0,0 coordinate in a font system to clarify:



The green line is the 1 em line. The blue line indicates coordinates where the Y value is zero in a font system. The red line indicates negative Y values.

This means that if the text was drawn at 0,0 in an SVG coordinate system all text above that base would be cut off, only descending text would be measured. For this reason the text is set to be drawn at 1em on the Y axis. That location in the SVG coordinate system corresponds to 0,0 in the font coordinate system.

For more information on the specifics of text positions in SVG see the Fonts, font tables, and baselines section of the SVG specification.