绘制复杂的字符串

时间:2013-07-26 22:57:28

标签: c# winforms

我有这样的代码,我尝试用它来绘制常规文本和网址。首先,我从文本中提取网址并为每个部分创建范围。

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的宽度足够大以容纳全文时,一切都很好。当我尝试使表单更薄并期望文本垂直扩展时,一切都很糟糕。

这里有什么问题? THX

0 个答案:

没有答案