---
title: "Get text selection rectangles in C#"
url: https://recursiveai.org/onefont/cookbook/layout-text-selection-rectangles/
description: "Map a logical text selection to visual highlight rectangles across left-to-right and right-to-left runs in C#. One shaped line, one font."
version: "1.4.0"
---

# Get text selection rectangles 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneFont) · [GitHub](https://github.com/recursive-ai-oss/onefont-csharp) · [Docs](https://recursiveai.org/onefont/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/cookbook/layout-text-selection-rectangles/layout-text-selection-rectangles.zip)

Map selected characters to their display positions on one mixed-direction line; for wrapped text, run this per line. Use the zip’s `bidi.ttf` (a Noto Sans subset with Hebrew), or your own font that covers the example text.

```shell
dotnet add package RecursiveAI.OneFont
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneFont;

var face = FontFace.Load(
    File.ReadAllBytes("bidi.ttf"));
// "a אבג": known LTR and RTL runs.
var left = TextShaping.ShapeRun("a ", face);
var right = TextShaping.ShapeRun("אבג", face,
    rightToLeft: true);
var width = left.Sum(c => c.Advance);
var gap = right[^1].Advance; // Unselected ג.
var tail = right.Take(2).Sum(c => c.Advance);
var h = face.Metrics.Ascender
    - face.Metrics.Descender;
// Select "a אב". Each tuple is x, y, w, h.
Console.WriteLine((0, 0, width, h));
Console.WriteLine((width + gap, 0, tail, h));
```

Unzip [the example](https://recursiveai.org/onefont/cookbook/layout-text-selection-rectangles/layout-text-selection-rectangles.zip), then `dotnet run`.

The snippet hardcodes the left-to-right and right-to-left runs for `a אבג`. The full program below shows how to derive the runs from the text.

Prints `(x, y, width, height)` in font units for the selection `a אב` within `a אבג`.

```text
(0, 0, 821, 2112)
(1195, 0, 1204, 2112)
```

## The full program

This version derives the runs from the line’s bidirectional levels, then uses the logical range `[0, 4)` to build rectangles in visual order. It prints merged rectangles at a font size of 20 px.

```csharp
using OneFont;

var face = FontFace.Load(
    File.ReadAllBytes("bidi.ttf"));
const string text = "a אבג";
var levels = TextShaping.GetBidiLevels(
    text, TextDirection.Auto, out _);
var cells = new List<(int Start, int End,
    int Advance, byte Level)>();
for (int from = 0; from < text.Length;)
{
    int to = from + 1;
    while (to < text.Length &&
           levels[to] == levels[from]) to++;
    var run = TextShaping.ShapeRun(
        text.AsSpan(from, to - from), face,
        rightToLeft: (levels[from] & 1) != 0);
    foreach (var cluster in run)
    {
        int start = from + cluster.Start;
        cells.Add((start, start + cluster.Length,
            cluster.Advance, levels[from]));
    }
    from = to;
}
var order = TextShaping.GetVisualOrder(
    cells.Select(cell => cell.Level).ToArray());
var ranges = new List<(int Left, int Right)>();
const int selectionStart = 0, selectionEnd = 4;
int x = 0;
foreach (int index in order)
{
    var cell = cells[index];
    int right = x + cell.Advance;
    if (selectionStart < selectionEnd && cell.Start < selectionEnd && selectionStart < cell.End && right > x)
    {
        if (ranges.Count > 0 && ranges[^1].Right == x)
            ranges[^1] = (ranges[^1].Left, right);
        else
            ranges.Add((x, right));
    }
    x = right;
}

var scale = 20.0 / face.UnitsPerEm;
var height = (face.Metrics.Ascender - face.Metrics.Descender) * scale;
foreach (var (left, right) in ranges)
    Console.WriteLine(FormattableString.Invariant(
        $"x={left * scale:F2}, y=0.00, w={(right - left) * scale:F2}, h={height:F2} px"));
```

```text
x=0.00, y=0.00, w=16.42, h=42.24 px
x=23.90, y=0.00, w=24.08, h=42.24 px
```

The gap between the rectangles belongs to the unselected `ג`. The example uses cluster advances, not outlines, and highlights the whole cluster when selection touches any part of it. The range check paints nothing for an empty selection.

## Variations

**Select the whole line.** In the full program replace the `selectionStart` and `selectionEnd` declaration with:

```csharp
int selectionStart = 0, selectionEnd = text.Length;
```

```text
x=0.00, y=0.00, w=47.98, h=42.24 px
```

## Related recipes

- [Shape mixed-direction text in C#](https://recursiveai.org/onefont/cookbook/right-to-left-text/)
- [Find caret positions and hit-test text in C#](https://recursiveai.org/onefont/cookbook/caret-positions/)

<!-- article -->

## The short answer

Keep each cluster’s original string range and place clusters in display order. For each cluster whose range overlaps the selection, emit its visual x interval using its shaped advance. Merge neighboring intervals if their edges touch. A single string range may produce several rectangles, even when all of the text is on one line.

## Why can a text selection have two highlight rectangles on one line?

In `a אבג`, the Hebrew letters are stored in reading order, but appear in reverse order when you scan the line from its left edge. The selected `א` and `ב` appear to the right of the unselected `ג`, while the selected `a ` appears to its left. Drawing one rectangle between the smallest and largest selected x positions would paint the unselected letter as well. The [Unicode Bidirectional Algorithm](https://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels) defines how the resolved levels are reordered for display.

To keep the two orders straight, the example shapes a run with `rightToLeft: true` for an odd bidi level. `ShapeRun` still returns its clusters in logical order. The code offsets each `Start` by the run’s start within the line, collects the levels in the same logical order, and calls `GetVisualOrder` once. Don’t reverse the right-to-left clusters before that call; it would reverse them twice.

## How do you calculate rectangles to highlight selected text?

Use half-open UTF-16 ranges: the selection includes `start` and excludes `end`. A nonempty range overlaps a cluster when its start comes before the cluster’s end and its end comes after the cluster’s start. This calculation intentionally highlights complete shaped clusters, including a ligature when only one of its letters is selected. It doesn’t calculate caret positions inside ligatures.

Walk all clusters, not just selected ones, so the pen advances over unselected characters and the gaps stay in the right places. The width of the rectangle is an advance, so a selected space can have a visible highlight even though it has no outline. The height comes from the line metrics; use your renderer’s actual line box if it already has one. For wrapped text, use the final visual placement for each line and compute that line’s rectangles separately. This example doesn’t perform wrapping or lay out explicit bidi controls.
