Query Glyph Bounding Boxes in FontForge Python

This guide explains how to query glyph bounding boxes using the FontForge Python extension. By loading a font and accessing individual glyph objects, you can retrieve coordinate limits representing the visual boundaries of any character using the built-in boundingBox() method.

Accessing the Glyph Bounding Box

In FontForge, a glyph's bounding box is queried through the glyph.boundingBox() method. This method returns a 4-element tuple of floating-point numbers or integers representing the coordinate boundaries in font units: (xmin, ymin, xmax, ymax).

  • xmin: The leftmost coordinate of the glyph contours.
  • ymin: The lowest coordinate of the glyph contours.
  • xmax: The rightmost coordinate of the glyph contours.
  • ymax: The highest coordinate of the glyph contours.

Basic Code Example

To query the bounding box of a specific glyph from a font file, use the following Python script:

import fontforge

# Open the font file
font = fontforge.open("path/to/your-font.sfd")

# Select a glyph by name or Unicode code point
glyph_name = "A"

if glyph_name in font:
    glyph = font[glyph_name]
    
    # Query the bounding box
    bbox = glyph.boundingBox()
    
    xmin, ymin, xmax, ymax = bbox
    print(f"Bounding Box for '{glyph_name}':")
    print(f"  xmin: {xmin}")
    print(f"  ymin: {ymin}")
    print(f"  xmax: {xmax}")
    print(f"  ymax: {ymax}")
    
    # Calculate dimensions
    width = xmax - xmin
    height = ymax - ymin
    print(f"  Width: {width}")
    print(f"  Height: {height}")
else:
    print(f"Glyph '{glyph_name}' not found in the font.")

# Close the font when finished
font.close()

Specifying Layers

By default, glyph.boundingBox() calculates the bounding box for the active layer (usually the foreground). If your font contains multiple layers and you need coordinates from a specific layer, switch the active layer on the glyph before querying:

# Query a specific layer (e.g., "Back")
glyph.activeLayer = "Back"
back_bbox = glyph.boundingBox()

# Switch back to Foreground
glyph.activeLayer = "Fore"
fore_bbox = glyph.boundingBox()

If a glyph contains no contours or references (such as a space character), boundingBox() typically returns (0.0, 0.0, 0.0, 0.0).