Recursive AI

Truncate shaped text with an ellipsis 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.

Cut at whole characters, then shape the prefix and … together. For this left-to-right example, use the zip’s sans.ttf (DejaVu Sans), or point the snippet at any .ttf on disk that covers your label and the ellipsis.

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"));
const string text = "e\u0301😀 menu";
var cuts = TextSegmentation
    .GetGraphemeBoundaries(text);
var candidates = cuts.SkipLast(1).Reverse()
    .Select(end => text[..end] + "…")
    .Prepend(text);
var label = candidates.FirstOrDefault(value =>
    TextShaping.ShapeRun(value, face)
        .Sum(c => (double)c.Advance)
        * 20 / face.UnitsPerEm <= 56);
Console.WriteLine(label ?? "");

Unzip the example, then dotnet run.

The snippet assumes the default dotnet new console template, with implicit usings enabled.

Prints the label fitted to 56 px at a font size of 20 px.

Text
é😀…

The full program

The program shapes e\u0301😀 menu in DejaVu Sans. The opening e and its combining acute accent are separate code points; the emoji takes two UTF-16 code units. The program tries five widths, including one too narrow for the ellipsis.

C#
using System.Globalization;
using OneFont;
 
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var face = FontFace.Load(File.ReadAllBytes("sans.ttf"));
const string label = "e\u0301😀 menu";
foreach (double limit in new[] { 56.0, 52.0, 28.0, 12.0, 160.0 })
{
    string display = Ellipsize(label, limit);
    Console.WriteLine($"{limit,3:F0} px: [{display}] ({Width(display):F2} px)");
}
 
string Ellipsize(string value, double limit)
{
    if (Width(value) <= limit)
        return value;
    var boundaries = TextSegmentation.GetGraphemeBoundaries(value);
    for (int index = boundaries.Length - 2; index >= 0; index--)
    {
        string candidate = value[..boundaries[index]] + "…";
        if (Width(candidate) <= limit)
            return candidate;
    }
    return "";
}
 
double Width(string value)
{
    var clusters = TextShaping.ShapeRun(value, face);
    if (clusters.Any(cluster => cluster.HasMissingGlyph))
        throw new InvalidOperationException("The sample font is missing a glyph.");
    return clusters.Sum(cluster => (double)cluster.Advance)
        * 20 / face.UnitsPerEm;
}
Text
 56 px: [é😀…] (53.15 px)
 52 px: [é…] (32.30 px)
 28 px: […] (20.00 px)
 12 px: [] (0.00 px)
160 px: [é😀 menu] (96.65 px)

At 52 px the emoji is removed whole. At 28 px the accented letter is also removed whole. If even the ellipsis won’t fit, the program returns an empty string. If the font lacks a required glyph, the full example throws instead of measuring a missing-glyph box.

Variations

Make the label narrower. In the snippet at the top, replace the predicate’s <= 56 with <= 52:

C#
var label = candidates.FirstOrDefault(value =>
    TextShaping.ShapeRun(value, face)
        .Sum(c => (double)c.Advance)
        * 20 / face.UnitsPerEm <= 52);
Console.WriteLine(label ?? "");
Text
é…

The short answer

Shape and measure the original label first. If it doesn’t fit, try prefixes from longest to shortest, cutting only at grapheme boundaries. Shape each prefix with the ellipsis already appended and return the first candidate whose advance fits. This is single-line, left-to-right truncation: it keeps the beginning of the label and doesn’t insert another line.

How do you truncate a C# string with an ellipsis to a pixel width?

A character count isn’t a width. For the same font and size, two strings of the same length can have different glyph advances. The ellipsis also needs room. The code measures prefix + "…" as one string, with the same face and size it will use for the final label. The cut can change which substitutions and positioning the font applies at the new end of the text. Measuring the original prefix’s glyphs and adding a separately measured ellipsis would miss those changes.

The loop doesn’t assume that every additional character necessarily raises the final width. It measures each candidate in the order of preference. This is suitable for short labels. If the same label is used repeatedly, you can cache the result for the same font, size, and width instead of shaping the same candidates again.

How do you truncate text without splitting an emoji or combining mark?

Use TextSegmentation.GetGraphemeBoundaries. A Unicode grapheme cluster groups the code points that make up a user-perceived character. Here the cluster boundary skips the accent’s position and the middle of the emoji’s surrogate pair. An arbitrary Substring index need not be either of those safe break points.

A grapheme cluster isn’t necessarily the same as a shaped cluster. For example, a font can shape multiple letters as one ligature. This recipe may keep only the first letter of that ligature because it cuts at a text boundary and shapes the new string from scratch; it never slices the original glyph. For mixed-direction text, decide whether you mean the logical end or a visual edge before choosing what to discard. This example doesn’t lay out bidirectional paragraphs.

All onefont recipes