首页 > 解决方案 > 在winforms中突出显示换行文本

问题描述

我正在尝试在给定的范围内突出显示包装的文本。我可以实现预期的行为。如果搜索文本在单行中,并且如果搜索文本呈现为两行(换行)如下所示,我将面临问题,

空白区域也与搜索文本一起突出显示

我已经使用字符范围和 MeasureCharacterRanges 方法来查找文本区域的区域并排除与给定搜索文本不匹配的文本区域,但我找不到没有呈现文本的空白区域的区域,因此空白区域也与给定的搜索文本一起突出显示。

StringFormat stringFormat = new StringFormat(StringFormat.GenericDefault);
Font font = new Font("Segoe UI", 9F, FontStyle.Regular);

var searchText = string.IsNullOrEmpty(SearchText) ? string.Empty : SearchText;
int matchIndex = Text.IndexOf(searchText);
if (matchIndex != -1 && searchText.Length > 0)
{
    CharacterRange[] characterRange = new CharacterRange[]
    {
            new CharacterRange(0, matchIndex),
            new CharacterRange(matchIndex, searchText.Length),
            new CharacterRange(matchIndex + searchText.Length , Text.Length - matchIndex - searchText.Length),
    };


    //Set the range of characters to be measured.
    stringFormat.SetMeasurableCharacterRanges(characterRange);

    //Gets the regions of the measurable characters applied to the string format for the given text with in the text bounds.
    Region[] regions = e.Graphics.MeasureCharacterRanges(Text, font, e.ClipRectangle, stringFormat);

    var clipBounds = e.Graphics.ClipBounds;

    for (int i = 0; i < regions.Length; i++)
    {
        RectangleF bound = regions[i].GetBounds(e.Graphics);
        e.Graphics.SetClip(Rectangle.Ceiling(bound));
        for (int j = 0; j < regions.Length; j++)
        {
            if (j != i)
                e.Graphics.ExcludeClip(regions[j]);
        }

        Rectangle rbound = new Rectangle((int)bound.X, (int)bound.Y, (int)bound.Width, (int)bound.Height);
        Brush brush = new SolidBrush(Color.Yellow);
        if (i == 1)
            e.Graphics.FillRectangle(brush, rbound);
     }

    e.Graphics.SetClip(clipBounds);
}


// Paints the text.
e.Graphics.DrawString(Text, font, Brushes.Black, e.ClipRectangle);

以上是用于突出显示搜索文本的代码。

我找不到使用 MeasureCharacterRanges 概念排除空白区域的方法。任何人都可以分享排除剩余空白区域的想法吗?

标签: c#windowswinformsrenderingword-wrap

解决方案


推荐阅读