【发布时间】:2022-12-03 02:52:51
【问题描述】:
我正在尝试创建一个基于模式的彩色丰富文本框。
正文是:
Hey, This{Red} IS A {Cyan}sample. The {Green}color is green color
每个{ } 都包含一种颜色,它是下一个单词的样式:
嘿,这个是一个sample. The 颜色是绿色
Hey, This 默认颜色。
IS A 应该是红色。
sample. The 应该是青色。
color is green color 应该是绿色的。
这是我的代码:
// Hey, This{Red} IS A {Cyan}sample. The {Green}color is green color
// shown text should be:
// Hey, This IS A sample. The color is green
const string OriginalText = "Hey, This{Red} IS A {Cyan}sample. The {Green}color is green color";
const string ShownText = "Hey, This IS A sample. The color is green color";
const string Pattern = "(?<=\\{)(.*?)(?=\\})";
rtbMain.Text = ShownText;
rtbMain.SelectAll();
rtbMain.SelectionColor = Color.Black;
rtbMain.SelectionBackColor = Color.White;
Regex regex = new(Pattern, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(OriginalText);
if (matches.Count > 0)
{
var rtbText = rtbMain.Text;
var length = ShownText.Length;
var allMatches = new List<Match>();
for (int i = 0; i < matches.Count; i++)
{
var m = matches[i];
allMatches.Add(m);
Match nextMatch = null;
if (matches.Count > i + 1)
{
nextMatch = matches[i + 1];
}
var sum = GetSum();
var start = m.Index;
var currentLength = m.Length;
if (nextMatch != null)
{
var end = nextMatch.Index - start- sum;
rtbMain.Select(start- 1, end);
}
else
{
var currentIndex = OriginalText.IndexOf(m.Value);
rtbMain.Select(length - currentIndex, (length - currentIndex) - sum);
}
rtbMain.SelectionColor = GetColor(m.Value);
}
int GetSum()
{
return allMatches!.Select(m => m.Value.Length - 1).Sum();
}
Color GetColor(string color)
{
return Color.FromName(color);
}
}
else
{
Debug.WriteLine("No matches found");
}
由于 richtextbox 没有颜色标签,我不知道如何计算索引/长度的正确位置。
提前致谢。
【问题讨论】: