如何:在绘制的文本中设置制表位

更新:2007 年 11 月

通过调用 StringFormat 对象的 SetTabStops 方法,然后将该 StringFormat 对象传递给 Graphics 类的 DrawString 方法,可以设置文本的制表位。

说明:

尽管可以使用 TextFormatFlags.ExpandTabs 标志扩展现有的制表位,但 System.Windows.Forms.TextRenderer 不支持在绘制文本中添加新的制表位。

示例

下面的示例在 150、250 和 350 处设置制表位。然后,该代码显示用制表符分隔的名称和测验得分的列表。

下面的插图显示用制表符分隔的文本。

字体文本

下面的代码将两个参数传递给 SetTabStops 方法。第二个参数是包含制表位偏移量的数组。传递给 SetTabStops 的第一个参数是 0,它表明数组中的第一个偏移量从位置 0(边框的左边)测量。

Dim myText As String = _
   "Name" & ControlChars.Tab & _
   "Test 1" & ControlChars.Tab & _
   "Test 2" & ControlChars.Tab & _
   "Test 3" & ControlChars.Cr

myText = myText & "Joe" & ControlChars.Tab & _
                  "95" & ControlChars.Tab & _
                  "88" & ControlChars.Tab & _
                  "91" & ControlChars.Cr
myText = myText & "Mary" & ControlChars.Tab & _
                  "98" & ControlChars.Tab & _
                  "84" & ControlChars.Tab & _
                  "90" & ControlChars.Cr
myText = myText & "Sam" & ControlChars.Tab & _
                  "42" & ControlChars.Tab & _
                  "76" & ControlChars.Tab & _
                  "98" & ControlChars.Cr
myText = myText & "Jane" & ControlChars.Tab & _
                  "65" & ControlChars.Tab & _
                  "73" & ControlChars.Tab & _
                  "92" & ControlChars.Cr

Dim fontFamily As New FontFamily("Courier New")
Dim font As New Font( _
   fontFamily, _
   12, _
   FontStyle.Regular, _
   GraphicsUnit.Point)
Dim rect As New Rectangle(10, 10, 450, 100)
Dim stringFormat As New StringFormat()
Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255))
Dim tabs As Single() = {150, 100, 100, 100}

stringFormat.SetTabStops(0, tabs)

e.Graphics.DrawString(myText, font, solidBrush, RectangleF.op_implicit(rect), stringFormat)

Dim pen As Pen = Pens.Black
e.Graphics.DrawRectangle(pen, rect)

string text = "Name\tTest 1\tTest 2\tTest 3\n";
text = text + "Joe\t95\t88\t91\n";
text = text + "Mary\t98\t84\t90\n";
text = text + "Sam\t42\t76\t98\n";
text = text + "Jane\t65\t73\t92\n";

FontFamily fontFamily = new FontFamily("Courier New");
Font font = new Font(
   fontFamily,
   12,
   FontStyle.Regular,
   GraphicsUnit.Point);
Rectangle rect = new Rectangle(10, 10, 450, 100);
StringFormat stringFormat = new StringFormat();
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
float[] tabs = { 150, 100, 100, 100 };

stringFormat.SetTabStops(0, tabs);

e.Graphics.DrawString(text, font, solidBrush, rect, stringFormat);

Pen pen = Pens.Black;
e.Graphics.DrawRectangle(pen, rect);

编译代码

请参见

任务

如何:用 GDI 绘制文本

其他资源

使用字体和文本