如何:設定畫筆寬度和對齊

當您建立 Pen 時,可以將畫筆寬度當做建構函式的其中一個引數來提供。 您也可以使用 Width 類別的 Pen 屬性來變更畫筆寬度。

理論線的寬度為 0。 當您繪製寬度為 1 圖元的線條時,圖元會置中于理論線上。 如果您繪製的線條寬度超過一個圖元,則圖元會置中于理論線上,或出現在理論線的一側。 您可以設定 的 Pen 畫筆對齊屬性,以決定使用該畫筆繪製的圖元相對於理論線條的方式。

出現在下列程式碼範例中的值 CenterOutsetInset 是 列舉的成員 PenAlignment

下列程式碼範例會繪製一行兩次:一次黑色畫筆寬度為 1,一次是寬度為 10 的綠色畫筆。

變更手寫筆的寬度

  • 將 屬性的值 Alignment 設定為 Center (預設值),以指定以綠色畫筆繪製的圖元會以理論線為中心。 下圖顯示產生的行。

    A black thin line with green highlight.

    下列程式碼範例會繪製一個矩形兩次:一次黑色畫筆寬度為 1,一次是寬度為 10 的綠色畫筆。

    Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
    Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
    greenPen.Alignment = PenAlignment.Center;
    
    // Draw the line with the wide green pen.
    e.Graphics.DrawLine(greenPen, 10, 100, 100, 50);
    
    // Draw the line with the thin black pen.
    e.Graphics.DrawLine(blackPen, 10, 100, 100, 50);
    
    Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 1)
    Dim greenPen As New Pen(Color.FromArgb(255, 0, 255, 0), 10)
    greenPen.Alignment = PenAlignment.Center
    
    ' Draw the line with the wide green pen.
    e.Graphics.DrawLine(greenPen, 10, 100, 100, 50)
    
    ' Draw the line with the thin black pen.
    e.Graphics.DrawLine(blackPen, 10, 100, 100, 50)
    
    

變更手寫筆的對齊方式

  • 將 屬性的值 Alignment 設定為 Center ,以指定以綠色畫筆繪製的圖元會置中矩形的界限。

    下圖顯示產生的矩形:

    A rectangle drawn with black thin lines with green highlight.

    Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
    Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
    greenPen.Alignment = PenAlignment.Center;
    
    // Draw the rectangle with the wide green pen.
    e.Graphics.DrawRectangle(greenPen, 10, 100, 50, 50);
    
    // Draw the rectangle with the thin black pen.
    e.Graphics.DrawRectangle(blackPen, 10, 100, 50, 50);
    
    Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 1)
    Dim greenPen As New Pen(Color.FromArgb(255, 0, 255, 0), 10)
    greenPen.Alignment = PenAlignment.Center
    
    ' Draw the rectangle with the wide green pen.
    e.Graphics.DrawRectangle(greenPen, 10, 100, 50, 50)
    
    ' Draw the rectangle with the thin black pen.
    e.Graphics.DrawRectangle(blackPen, 10, 100, 50, 50)
    
    

建立內嵌畫筆

  • 修改上述程式碼範例中的第三個語句,以變更綠色畫筆的對齊方式,如下所示:

    greenPen.Alignment = PenAlignment.Inset;
    
    greenPen.Alignment = PenAlignment.Inset
    
    

    現在,寬綠色線條中的圖元會出現在矩形內部,如下圖所示:

    A rectangle drawn with black lines with the wide green line inside.

另請參閱