ZenosZeng 发表于 2012-10-31 19:00:00

在TextControl中测量文本长度

在多数系统中,我们经常会判断在指定的显示范围内是否能够显示下指定的文本长度,此时我们会用到GDI+提供的MeasureString方法。

在 TX Text Control 中测量文本长度的方法稍微有所不同,TX Text Control 有自己的的文本渲染机制,通过这种所见即所得的渲染机制才使得TX的文本编辑功能如此的优秀。
在 TX Text Control X8 版本中,WinForms和WPF系统中可以使用一个不可见的ServerTextControl组件,通过该组件可以得到文本的实际长度,下面的代码简单演示了该功能:
public int MeasureTextControlString(Selection Selection, string FormattingPrinter)
{
   int iLength;
      using (ServerTextControl tx = new ServerTextControl())
   {
         tx.Create();
         tx.PageSize.Width = 10000;
         tx.FormattingPrinter = FormattingPrinter;
          foreach (PropertyInfo property in Selection.GetType().GetProperties())
         {
             if (property.GetValue(Selection, null).ToString() == "")
                continue;

            property.SetValue(tx.Selection,
                  property.GetValue(Selection, null), null);
         }

          tx.SelectAll();

          return iLength = tx.TextChars.Bounds.Right -
               tx.TextChars.Bounds.Left;
   }
}

下面的代码演示了如何使用以上方法测量出文本的长度:
Selection newSelection = new Selection();
newSelection.Text = "Hello dWorld";
newSelection.FontSize = 600;
newSelection.FontName = "Wingdings";

int length = MeasureTextControlString(newSelection, textControl1.FormattingPrinter);
页: [1]
查看完整版本: 在TextControl中测量文本长度