代码改变世界

WPF 文本呈现(2)

2010-12-03 14:10  Clingingboy  阅读(1381)  评论(1编辑  收藏  举报

 

文本输出规则

比如输出Hello,可以多种输出方法.如下

  1. Hello
  2. He llo
  3. H e l l o

当都遵循一个原则,字符将从左到右输出,

如H(0,1),ell(1,3),o(4,1) 表示从索引值输出多少个字符.这个过程将一直持续下去直到段落结束为止

输出多彩文字

public override TextRun GetTextRun(int textSourceCharacterIndex)
{
  //typeof(Brushes).GetProperties()[0].GetValue()
    if (textSourceCharacterIndex >= _text.Length)
    {
        return new TextEndOfParagraph(1);
    }
    _currentRendering.TextColor = brushs[textSourceCharacterIndex] as SolidColorBrush;
    // Create TextCharacters using the current font rendering properties.
    if (textSourceCharacterIndex < _text.Length)
    {
        return new TextCharacters(
           _text,
           textSourceCharacterIndex,
           1,
           new GenericTextRunProperties(_currentRendering));
    }
    // Return an end-of-paragraph if no more text source.
    return new TextEndOfParagraph(1);
}

输出结果

image

每次从当前索引输出一个字符,每次更改字符属性的颜色

更改大小

image

每隔三次字符输出Winow单词

image

    _currentRendering.TextColor = brushs[textSourceCharacterIndex] as SolidColorBrush;
    _currentRendering.FontSize = textSourceCharacterIndex*12+12;
    return new TextCharacters(
       _text,
       textSourceCharacterIndex,
       3,
       new GenericTextRunProperties(_currentRendering));

结束段落

告诉段落结束的办法是在GetTextRun方法中返回TextEndOfParagraph,比如默认当索引字符等于输出字符长度时则认为段落结束
if (textSourceCharacterIndex > _text.Length)
{
    return new TextEndOfParagraph(1);
}

在段落添加额外的文字,在输出文字结束以后添加段落末尾的文字,如下图EndTextWord可以以自行的逻辑添加

image

var customEndText = "EndTextWord";
var gap = textSourceCharacterIndex - _text.Length;
if (gap >= 0 && gap < customEndText.Length)
{
    
    _currentRendering.FontSize = 24;
    return new TextCharacters(
       customEndText,
       0,
       customEndText.Length,
       new GenericTextRunProperties(_currentRendering));
}
if (gap >= customEndText.Length)
{
    return new TextEndOfParagraph(1);
}

多段落

如下文字

image

若窗体宽度不够的话,将换行显示

在TextLine调用Draw方法以后,若宽度不够,将只呈现部分文字,并有一个Length属性,然后可以根据Length属性继续呈现第二段文字.如下代码(仅做示例而用)

TextLine myTextLine = formatter.FormatLine(
    textStore,0,80,
    new GenericTextParagraphProperties(currentRendering),
    null);
myTextLine.Draw(dc, new Point(0, 0), InvertAxes.None);
myTextLine.Dispose();
// Draw second paragraph.
using (TextLine myTextLine2 = formatter.FormatLine(
    textStore,myTextLine.Length,80,
    new GenericTextParagraphProperties(currentRendering),
    null))
{
    myTextLine2.Draw(dc, new Point(0, 25), InvertAxes.None);
}

现在

image