c# - 在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 概念排除空白区域的方法。任何人都可以分享排除剩余空白区域的想法吗?
解决方案
推荐阅读
- asp.net-mvc - 如何创建一个全局函数然后在控制器上使用
- r - 获取 getSymbols 函数将包含的整个股票代码列表
- r - 替换数据框一列中的多个字符串
- sql - 详细记录查询上次价格
- qt5 - 如何在 Raspberry Pi3 上的 Qt5 上使用 qt-gstreamer 和 qtquick2videosink
- python - 访问熊猫数据框中每一行的列表的第二个元素
- c# - Sonarcube 不喜欢我的可序列化异常类的实现
- ios - Ionic Capacitor Deploy App on ios 13.3 device freeze splashscreen
- flutter - Flutter 从服务返回解析动态对象
- python - 如何将时间分成 10 分钟间隔并使用 Python 将其作为单独的列