我有这样的代码,我尝试用它来绘制常规文本和 url。首先,我从文本中提取 url 并为每个部分创建 Ranges。
private static readonly Font TextFont = new Font("Verdana", 10);
private readonly Regex RgUrl = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)",
RegexOptions.Multiline | RegexOptions.Compiled);
private void PaintComplexString(Graphics g)
{
List<CharacterRange> ranges = new List<CharacterRange>();
int start = 0;
// create separate ranges for URLs
foreach (Match match in RgUrl.Matches(_text))
{
if (start != match.Index)
ranges.Add(new CharacterRange(start, match.Index - start));
ranges.Add(new CharacterRange(match.Index, match.Length));
start = match.Index + match.Length;
}
if (start != _text.Length)
ranges.Add(new CharacterRange(start, _text.Length - start));
StringFormat format = new StringFormat(StringFormat.GenericTypographic);
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoClip;
format.SetMeasurableCharacterRanges(ranges.ToArray());
Region[] regions = g.MeasureCharacterRanges(_text, TextFont, ClientRectangle, format);
int index = 0;
foreach (Region region in regions)
{
string txt = _text.Substring(ranges[index].First, ranges[index].Length);
Debug.WriteLine(index + "*" + txt + "*");
Rectangle rc = Rectangle.Round(region.GetBounds(g));
g.DrawString(txt, TextFont, Brushes.Chocolate, rc, format);
g.DrawRectangle(Pens.BlueViolet, rc);
index++;
}
}
当 ClientRect 的宽度足够大以容纳全文时,一切都可以正常绘制。当我尝试使表单更薄并期望文本垂直扩展时,一切都非常糟糕。
这里有什么问题?谢谢