bounding box of n glyphs, given individual bboxes

2019-05-23 03:21发布

问题:

For specific reasons, I'm implementing my own font rendering, and an algorithm to compute the bounding box of a text by using bounding boxes of single glyphs, together with the respective advance, is needed. For clarification see this illustration:

For every of these N glyphs is given the relative bbox relative to the origin (xmin, xmax, ymin, ymax), and the advance (pseudocode):

int xmin[N], xmax[N], ymin[N], ymax[N], adv[N];

I will give the answer myself if noone bites.

回答1:

For the general case you won't be able to accurately measure a string using just the glyph bounding box and the advance width due to hinting, kerning, and ligatures which will significantly modify the sizes of glyphs and their spacing depending on their position in the string as well as the chosen font size.

The naive way to calculate the string length by iterating the glyphs and adding the advance width and xMin will only be correct for certain fonts at certain sizes and shouldn't be used if at all possible.

The easiest way to get font metrics is to use an established font rendering engine to either directly get the length of the text (if the API exposes that) or render the text to a surface and find the min/max pixel in the X/Y directions.