Recursive AI

Fit text into a fixed-size box in C#

onefont is a free, open-source font and text-shaping library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Fit a single line with the zip’s sans.ttf (Noto Sans). For wrapped text, check the fit of each line.

Terminal
dotnet add package RecursiveAI.OneFont

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneFont;
 
var face = FontFace.Load(
    File.ReadAllBytes("sans.ttf"));
var run = TextShaping.ShapeRun("AV café", face);
double advance = run.Sum(
    c => (double)c.Advance);
double line = face.Metrics.Ascender
    - face.Metrics.Descender;
var scale = Math.Min(100 / advance, 24 / line);
var size = scale * face.UnitsPerEm;
Console.WriteLine(FormattableString.Invariant(
    $"Size: {size:F2} px"));

Unzip the example, then dotnet run.

Prints the font size for AV café in a 100 × 24 px box, rounded for display.

Text
Size: 17.62 px

The total advance is how far the pen moves across the shaped line. The signed descent is negative because it measures below the baseline, so subtract it from the ascent to get the line height. Units per em tell you how many of the font’s design units make up one em, which is one font size.

The full program

The program shapes the label once, then checks how much room it uses in two rectangles. The first is limited by height; the second by width.

C#
using System.Globalization;
using OneFont;
 
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var face = FontFace.Load(File.ReadAllBytes("sans.ttf"));
const string text = "AV café";
var run = TextShaping.ShapeRun(text, face);
if (run.Any(cluster => cluster.HasMissingGlyph))
    throw new InvalidOperationException("Choose a font that covers the label.");
 
double advance = run.Sum(cluster => (double)cluster.Advance);
double line = face.Metrics.Ascender - face.Metrics.Descender;
foreach (var (width, height) in new[] { (100.0, 24.0), (48.0, 24.0) })
{
    double scale = Math.Min(width / advance, height / line);
    double size = scale * face.UnitsPerEm;
    double usedWidth = advance * scale;
    double usedHeight = line * scale;
    Console.WriteLine($"{width:F0}×{height:F0} px box: size {size:F2} px");
    Console.WriteLine($"  Uses {usedWidth:F2}×{usedHeight:F2} px");
    if (usedWidth > width + 1e-9 || usedHeight > height + 1e-9)
        throw new InvalidOperationException("The line does not fit.");
}
Text
100×24 px box: size 17.62 px
  Uses 60.05×24.00 px
48×24 px box: size 14.08 px
  Uses 48.00×19.18 px

Use the unrounded size for drawing. For a control with padding, subtract it first. If the font doesn’t cover the label, the example throws rather than sizing for missing-glyph boxes.

Variations

Use a whole-pixel font size. If your renderer only takes whole pixels, round down so the size still fits. In the snippet at the top, replace the size calculation with:

C#
var size = Math.Floor(scale * face.UnitsPerEm);
Text
Size: 17.00 px

The short answer

Shape the label once. Divide the box width by the total advance, and divide the box height by the ascent minus the signed descent. Take the smaller of the two scales and multiply it by the face’s units per em. The result is the largest size for which both the advance and the metric line box fit, without changing the text.

How do you calculate the font size to fit text in a rectangle?

OneFont gives you design units, not pixels. A scale of size / UnitsPerEm converts both the horizontal advances and the vertical metrics to pixels. Invert that relationship: available pixels divided by required design units gives the maximum scale on that axis. Taking the smaller scale lets you use the same size on both axes without stretching the text. At 100 × 24 px the label has width left over; at 48 × 24 px height is left over instead.

Use a positive interior width and height and a face with usable metrics. A zero-advance run, such as an empty label, imposes no width restriction; don’t use a zero denominator to calculate a width limit. If the renderer accepts only whole pixel sizes, round down, not to the nearest integer. If the result falls below your minimum legible size, give the label more room, wrap it, or choose to truncate it instead.

Does a font size that fits the line also prevent glyph clipping?

Not by itself. An advance tells you how far the drawing pen moves, not how far an italic glyph or mark reaches. The face’s ascent and descent similarly describe the line box, not the outline of every glyph in the label. The example checks an advance and a line height, without the between-line LineGap. For strict clipping at all four edges, measure each positioned outline’s TightBox() and include any overhang beyond the advance or the vertical line box before deciding what fits. Keep the same font and shaping settings in measurement and drawing; changing either can change the design-unit widths.

This formula is for one fixed shaped line. If the label can wrap, changing the size can also change where the lines break and how many there are. In that case, reflow when you try a new size and check the widths and the height of the resulting block.

All onefont recipes