共用方式為


HOW TO:在已繪製的文字中設定定位停駐點

更新:2007 年 11 月

您可以經由呼叫 StringFormat 物件的 SetTabStops 方法,然後將該 StringFormat 物件傳遞至 Graphics 類別的 DrawString 方法,以設定文字的定位停駐點。

注意事項:

System.Windows.Forms.TextRenderer 不支援將定位停駐點加入至繪製的文字,但您可以使用 TextFormatFlags.ExpandTabs 旗標擴充現有的定位停駐點。

範例

下列範例會在 150、250 和 350 設定定位停駐點 (Tab Stop),然後程式碼會顯示名稱和考試成績的索引標籤式清單。

下圖顯示的是索引標籤式文字。

字型文字

下列程式碼會將兩個引數傳遞至 SetTabStops 方法。第二個引數是包含定位點位移 (Offset) 的陣列。傳遞至 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);

編譯程式碼

請參閱

工作

HOW TO:使用 GDI 繪製文字

其他資源

使用字型和文字